var allowPageBreakMidVerse = false;
var slightVerticalSpace = allowPageBreakMidVerse? '[0.0514in]' : '*[0.0514in]';
var processUrl = '../processPsalm.php';
var dirUrl = '../dir.php';
var gabcQueue = [];
var gabcProcessing = [];
var maxConcurrent = 5;

var regBold = /\|(\S(?:.*?\S)?)\|/gi;
var regItalic = /_(\S(?:.*?\S)?)_/gi;
var regTeXDiacritics = /\\([`'^"H~ckl=b.druvt])({([^}]+)}|\b\S)/g;
var replaceEscapedDiacritics = function(text){
  return text.replace(regTeXDiacritics,function(){
    return arguments[3] || arguments[2];
  });
}

var selType=0,
    _types=['Square','Modern'];
function callSectionPdf(e){
  if(e && typeof(e.preventDefault)=="function"){
    e.preventDefault();
  }
  if(typeof(activeSection)=='undefined') return;
  callPrereqs(function(){
    $newForm = $('<form target="_blank" method="post" action="../processPsalm.php">\
<input type="hidden" value="false" name="croppdf"/>\
<input type="hidden" name="edition"/>\
<input type="hidden" name="supertitle"/>\
<input type="hidden" name="title"/>\
<input type="hidden" name="subtitle" value="section preview"/>\
<input type="hidden" name="marginalnumbersize" value="'+$('#pdff_rbMarginalNumberSize').val()+'"/>\
<input type="hidden" name="marginalnumberalignment" value="'+$('#pdff_rbMarginalNumberAlignment').val()+'"/>\
<input type="hidden" name="swapmarginalnumbers" value="'+$('#pdff_cbSwapMarginalNumbers').val()+'"/>\
<input type="hidden" name="boldmarginalnumbers" value="'+$('#pdff_cbBoldMarginalNumbers').val()+'"/>\
<input type="hidden" name="footer"/>\
<input type="hidden" name="subsetfonts" value="1"/>\
<input type="hidden" name="template" value="'+$('#pdff_txtTemplate').val()+'"/>\
<input type="hidden" name="fmt" value="pdf"/>\
</form>');
    $newForm.append($('input[type=hidden][id^=pdff_][section='+activeSection+']').clone());
    $input = $('<input type="hidden" name="engravings">').val(JSON.stringify([jsonForSectionEngravings(activeSection)]));
    $newForm.append($input);
    $input = $('<input type="hidden" name="verses">').val(JSON.stringify([jsonForSectionVerses(activeSection)]));
    $newForm.submit();
  });
}
function extraJsonForSection(s){
  var result = {};
  var $table = $('tr[section='+s+']');
  switch(sectionType[s]){
    case 'antiphon-tone':
      result.mediant = $('#selMediant_'+s).val();
      result.termination = $('#selTermination_'+s).val();
      result.mode = $('#txtMode_'+s).val();
      result.text = $('#txtEngraving_'+s).val();
      result.overrideTextLeft = $('#txtOverrideTextLeft_'+s).val();
      result.overrideTextRight = $('#txtOverrideTextRight_'+s).val();
      result.psalmToneWidth = $('#txtPsalmToneWidth_'+s).val();
      var sigliaLeft = [];
      var sigliaRight = [];
      $('input[name=sigliaLeft]',$table).each(function(){
        if(this.checked) sigliaLeft.push(this.value);
      });
      $('input[name=sigliaRight]',$table).each(function(){
        if(this.checked) sigliaRight.push(this.value);
      });
      result.sigliaLeft = sigliaLeft.join(', ');
      result.sigliaRight = sigliaRight.join(', ');
      break;
    case 'hymn':
      $('input[name^=genrenumberleftright_]',$table).each(function(){
        if(this.checked) result.genrenumberleftright = this.value;
      });
      result.verseseparators = $('input[id^=txtVerseSeparators_]',$table).val().split(/\s*[,;]\s*/).map(function(e,i){
        return parseInt(e.trim()) || null;
      });
      var index;
      while((index = result.verseseparators.indexOf(null)) >= 0) {
        result.verseseparators.splice(index,1);
      }
      result.extraVersesColumnLengths = $('input[name=extraVersesColumnLengths]', $table).val().split(/\s*[,;]\s*/).map(function(e,i){
        return parseInt(e.trim()) || null;
      });
      var index;
      while((index = result.extraVersesColumnLengths.indexOf(null)) >= 0) {
        result.extraVersesColumnLengths.splice(index,1);
      }
      result.oneColumnExtraVerses = $('input[name=oneColumnExtraVerses]', $table).is(':checked');
      result.hideMetadata = $('input[name=hideMetadata]', $table).is(':checked');
      result.hideTitle = $('input[name=hideTitle]', $table).is(':checked');
      break;
    case 'hairline':
      result.text = $('#txtHairlineText_'+s).val();
      result.margin = $('#txtHairlineMargin_'+s).val();
      break;
    case 'engraving-Square':
    case 'engraving-Modern':
      result.twoColumnVerses = $('#cbTwoColumnVerses_'+s).is(':checked');
      result.engravingHeader = $('#txtEngravingHeader_'+s).val();
      break;
  }
  return result;
}
function jsonForSectionEngravings(s){
  var curSubsection = [];
  $('table[section='+s+'][engraving]').each(function(){
    var cur = {};
    curSubsection.push(cur);
    if($(this).is('.main')) {
      cur.main = true;
    }
    $('input[name]:not([name=siglia]),select[name]',this).each(function(){
      var $this = $(this);
      if(this.type=='checkbox') {
        if(this.name) cur[this.name] = (this.checked && ($this.attr('onvalue') || true)) || $this.attr('offvalue') || false;
      } else if(this.type=='radio') {
        if($this.prop('checked')) {
          cur[this.name.match(/^([^_]*)(?:_|$)/)[1]] = $this.val();
        }
      } else {
        cur[this.name] = $this.attr('disabled')? false : this.value;
      }
    });
    var siglia = [];
    $('[id^=cbSiglia]',this).each(function(){
      if(this.checked) siglia.push(this.value);
    });
    cur.siglia = siglia.join(', ');
  });
  return curSubsection;
}
function jsonForSectionVerses(s){
  var curSubsection = [];
  $('table[section='+s+'][verse]').each(function(){
    var cur = {};
    var $this = $(this);
    curSubsection.push(cur);
    if($this.attr('type')) {
      cur.type = $this.attr('type');
    }
    $('input[name],select[name],textarea',this).each(function(){
      var $this = $(this);
      if(this.type=='checkbox') {
        if(this.name) cur[this.name] = (this.checked && ($this.attr('onvalue') || true)) || $this.attr('offvalue') || false;
      } else if(this.type=='radio') {
        if($this.prop('checked')) {
          cur[this.name.match(/^([^_]*)(?:_|$)/)[1]] = $this.val();
        }
      } else {
        var data = $this.data('value');
        cur[this.name] = (typeof(data)=='string')?
          data : ($this.attr('disabled')? false : this.value);
      }
    });
  });
  return curSubsection;
}
function callPrereqs(callback){
  var engravings = [];
  var verses = [];
  $('input[id^=pdff_][name="sectionnum[]"]').each(function(){
    var s = parseInt($(this).attr('section'));
    engravings.push(jsonForSectionEngravings(s));
    verses.push(jsonForSectionVerses(s));
    $('input[type=hidden][name="sectionJson[]"][section='+s+']').val(JSON.stringify(extraJsonForSection(s)));
  });
  $('input[type=hidden][name=engravings]').val(JSON.stringify(engravings));
  $('input[type=hidden][name=verses]').val(JSON.stringify(verses));

  var $buttons = $('[id^=createSection]:not([disabled])');
  var count = $buttons.length;
  var returns = 0;
  if(count == 0) {
    if(typeof(callback)=='function') callback(engravings);
  } else {
    var $btn = $buttons.first();
    var s = $btn.parents('tr').attr('section')
    hideAllSections(s);
    showSection(s);
    $btn.focus()
/*    $buttons.each(function(){
      createNewSection.apply(this,[function(){
        returns++;
        if(returns==count && typeof(callback)=='function') callback();
      }]);
    });
*/
  }
}


function callGregorioPdf(e){
  if(e && typeof(e.preventDefault)=="function"){
    e.preventDefault();
  }
  var subsetFonts = (e && e.subsetfonts===true)?'1':'';
  if(this.id=='lnkSmallPDF') subsetFonts = '1';
  $('#pdff_subsetfonts').val(subsetFonts);
  var publish = (e && e.publish===true)?'1':'';
  if(this.id=='lnkPublish') publish = '1';
  $('#pdff_publish').val(publish);
  callPrereqs(function(){
    $('[id^=cbPsalmIntact]').each(function() {
      var $this = $(this),
          sectionNum = $this.parents('tr').attr('section') || '';
      if(this.checked){
        $("#pdff_txtPsalmVerse_" + sectionNum).val('');
      }
    });
    $("#pdfForm").submit();
  });
}

function callGregorioImage(e){
  if(e && typeof(e.preventDefault)=="function"){
    e.preventDefault();
  }
  callPrereqs(function(){
    $('[id^=cbPsalmIntact]').each(function() {
      var $this = $(this),
          sectionNum = $this.parents('tr').attr('section') || '';
      if($this.prop('checked')){
        $("#imgf_txtPsalmVerse_" + sectionNum).val('');
      }
    });
    $("#imgForm").submit();
  });
}

function callGregorio(e){
  if(e && typeof(e.preventDefault)=="function"){
    e.preventDefault();
  }
  $('#pdff_subsetfonts').val('');
  var publish = (e && e.publish===true)?'1':'';
  if(this.id=='lnkPublish') publish = '1';
  $('#pdff_publish').val(publish);
  var action = publish? 'Publishing' : 'Saving';
  callPrereqs(function(){
    $('[id^=cbPsalmIntact]').each(function() {
      var $this = $(this),
          sectionNum = $this.parents('tr').attr('section') || '';
      if($this.prop('checked')){
        $("#pdff_txtPsalmVerse_" + sectionNum).val('');
      }
    });
    processGabc(getVars(), action);
  });
}

function getVars() {
  return $("#pdfForm input").serializeArray();
}

function GabcJob(vars,action){
  this.vars = vars;
  this.action = action || "Saving";
  var job = this;
  var varMap = {};
  $.each(vars,function(){
    if(!(this.name in varMap)) varMap[this.name] = this.value;
  });
  job.filename = varMap.filename || getFilenameForTitleSuperSub(varMap.title,varMap.supertitle,varMap.subtitle);
  if(!this.filename)this.filename="untitled";
  var notification = this.notification = $("<div>Queued "+this.filename+"...</div>");
  this.fadeNotification=function(e){
    if(typeof(e)=='object') {
      if(e.which==3 || e.ctrlKey || e.altKey || e.shiftKey) {
        e.preventDefault();
      } else {
        return;
      }
    }
    notification.fadeOut(function(){
      notification.remove();
      if($("#notifications").children().length == 0) {
        $("#notificationsBG,#notifications").hide();
      }
    });
  };
}

GabcJob.prototype.queue = function(){
  $("#notifications").append(this.notification);
  $("#notificationsBG,#notifications").show();
  if(gabcProcessing.length < maxConcurrent) {
    this.run();
  } else {
    gabcQueue.push(this);
  }
};
GabcJob.prototype.run = function(){
  gabcProcessing.push(this);
  var vars = [
    {name:'croppdf',
      value:false
    },
    {name:'save',
      value:true
    }
  ];
  $.merge(vars, this.vars);
  this.notification.text(this.action + ' '+this.filename+'...');
  $.post(processUrl,vars)
    .complete(this.postCompleted)
    .statusCode({301:this.redirected}).gabcJob = this;
};
GabcJob.prototype.postCompleted = function(e,result){
  var i;
  var job = e.gabcJob;
  while((i = gabcProcessing.indexOf(job)) >= 0){
    gabcProcessing.splice(i,1);
  }
  var nextGabc = gabcQueue.shift();
  if(nextGabc)nextGabc.run();
  if(result=="success"){
    if(e.getResponseHeader("Content-Type")=="text/plain"){
      var match = e.responseText.match(/^Location:\s*(.+)$/);
      if(match) {
        var url = match[1];
        job.notification.append("<span>SUCCESS: <a href='"+url+"'>"+url+"</a></span>");
      } else {
        job.notification.append("<span style='color:red;font-weight:700'>ERROR:</span><blockquote>"+e.responseText+"</blockquote>");
      }
    } else {
      job.notification.append("done!");
      setTimeout(job.fadeNotification,1000);
      return;
    }
  } else {
    job.notification.append("<span style='color:red;font-weight:700'>"+result+":</span><blockquote>"+e.responseText+"</blockquote>");
  }
  job.notification.mousedown(job.fadeNotification);
};

function processGabc(vars,action){
  new GabcJob(vars,action).queue();
}

function docKeyDown(e){
  if(e.ctrlKey) {
    if(e.which==90){//Z
      e.preventDefault();
      if(e.shiftKey){
        callSectionPdf();
      }
    } else if(e.which==83) {//S
      //save
      e.preventDefault();
      callGregorio();
    } else if(e.which==80){//P
      //Preview
      e.preventDefault();
      if(e.shiftKey){
        callGregorioPdf();
      } else {
        callGregorioImage();
      }      
    } else if(e.which==67){//C
      if(e.shiftKey){
        clearFields();
      }
    } else if(e.which==68){//D
      e.preventDefault();
      callGregorioPdf({subsetfonts:true});
    } else if(e.which==85){//U
      if(e.shiftKey) {
        callGregorio({publish:true});
      }
    }
  }
}


function setTypeLabel(){
  $("#btnType").button("option","label",_types[selType]);
}

function hideImage(){
  $("#overlay,#chant-image").hide();
}

function lightboxImage(){
  $ci=$("#chant-image-iframe");
  $i=$("img",$ci[0].contentDocument);
  $($ci[0].contentDocument&&$ci[0].contentDocument.body).css("margin","2px");
  $($ci[0].contentDocument).click(hideImage);
  var width="7in";
  var height="70%";
  if($ci[0].contentDocument && $i[0]){
    width=$i[0].width+4;
    height=$i[0].height+4;
  }
  //$ci.css("width","10000").css("height","10000");
  $ci.css("height",height)
    .css("width",width)
    .css("margin-top",Math.min($ci.parent().height(),$ci.height())*(-0.33))
    .css("margin-left",Math.min($ci.parent().width(),$ci.width())/(-2));
  $("#chant-image,#overlay").show();
}

function processVerseOld(verse){
  var lines = verse.split('\n');
  var val = '\\begin{patverse}\\flagverse{\\Vbar}';
  var indentpattern = [];
  v = false;
  for(var i=0; i < lines.length; ++i){
    var line = lines[i],
        nextLine = lines[1 + i];
    if(line.match(/^\s*$/)) {
      if(v) {
        val += '\n\n\\flagverse{\\Vbar}';
        v = false;
      }
    } else {
      val += '\n' + line + '\\\\';
      val += ((nextLine != undefined) && nextLine.match(/^\s*$/))? '!' : 
                ((nextLine != undefined) && nextLine.match(/^\S/))? slightVerticalSpace : '*';
      v = true;
      indentpattern.push(line.match(/^\s/)? 1 : 0);
    }
  }
  val += '\\end{patverse}';
  val = '\\indentpattern{' + indentpattern.join('') + '}' + val;
  return val.replace(regBold,'\\textbf {$1}').replace(regItalic,'{\\it $1}');
}
function processVerse(v) {return v;}

function processBoldItalicOld(text) {
  return text.replace(regBold,'\\textbf {$1}').replace(regItalic,'{\\it $1}');
}
function processBoldItalic(t){return t;}
function updateSelSpace() {
  var $this = $(this);
  var section = $this.parents('tr').attr('section');
  if(!section) {
    var $table = $this.parents('table[section]');
    section = $table.attr('section');
  }
  $('#imgf_sectionID_'+section+',#pdff_sectionID_'+section).val(this.value);
}
function txtChanged(unused,elem){
  var $elem = $(elem);
  var $this = $(this);
  var section = $this.parents('tr').attr('section');
  if(!section) {
    var $table = $this.parents('table[section]');
    section = $table.attr('section');
  }
  if($elem.length) $this = $elem;
  elem = $this[0];
  var val = $this.val();
  if($this.attr('type')=='radio') {
    elem = $this.parent().get(0);
  } else if(elem.id.match(/^txtGenre_\d+$/)) {
    checkAlleluiaSectionName(section);
  } else if($this.attr('type')=='checkbox') {
    val = this.checked? 1 : 0;
  }
  $elem = $('#imgf_' + elem.id + ',#pdff_' + elem.id);
  $elem.val(val);
}

function indexOfGloryBe(text){
  var noWhitespace = text.replace(/[\s_|]+/g,'');
  if(noWhitespace.slice(-gloryBeTextNoWhitespace.length) == gloryBeTextNoWhitespace) {
    text = text.replace(/\r\n/g,'\n');
    return text.lastIndexOf('Glory be',text.length - gloryBeTextNoWhitespace.length);
  }
  return -1;
}

setDefaultNumberVersesIfChanged = (function(){
  var multiVersesLastTime = [];
  return function(e) {
    var $this = $(this);
    var section = $this.parents('tr').attr('section') || '';
    var curVal = $this.val();
    var match = curVal.match(/\w.*\n\s*\n.*\w/);
    if(!((section in multiVersesLastTime) && !(!multiVersesLastTime[section] ^ !match))) {
      if(!($('#rbMarkVersesNothing_' + section).prop('checked') || $('#rbMarkVersesReferenceNumbers_' + section).prop('checked'))) {
        $('#rbMarkVerses'+(match?'Numbers':'Versicle')+'_' + section).attr('checked',true).change();
      }
      multiVersesLastTime[section] = match;
    }
  };
})()

psalmVerseKeyUp = function(e) {
  var $this = $(this);
  var $table = $this.parents('table[section]');
  var section = $table.attr('section');
  var verse = $table.attr('verse');
  var sectionVerse = section + '_' + verse;
  var $cb = $("#cbPsalmIntact_" + sectionVerse);
  var original = $this.data('original');
  var curVal = $this.val();
  var checked = (original == curVal);
  $cb.attr('checked', checked);
  $this.attr('title', checked? '' : original);
  var val = '';
  var match = curVal.match(/\w.*\n\s*\n.*\w/);
  setDefaultNumberVersesIfChanged.apply(this,[e]);
  if(!checked){
    val = curVal.replace(/\s+$/,'');
    gloryBeChecked = false;
    var index = indexOfGloryBe(val);
    if(index>=0) {
      gloryBeChecked = true;
      val = val.slice(0,index).replace(/\s+$/,'');
    }
    $("#cbGloryBe_" + sectionVerse).attr('checked',gloryBeChecked);
  }
  $("#pdff_" + this.id + ",#imgf_" + this.id).val(val);
  $(this).data('value',val);
};

/*function updateSpaceBelowChant(e,ui) {
  $('#imgf_' + this.id + ',#pdff_' + this.id).val(ui.item.value.slice(0,-2));
}*/

function updateEdition(e,ui){
  $('#imgf_' + this.id + ',#pdff_' + this.id).val(ui.item.value);
  updateTemplateLink(ui.item.value);
}

function triggerChangeFromAutocomplete(e,ui){
  $(this).val(ui.item.value).change();
}

function txtVerseFileChanged(e){
  $a = $(this).parents('tr').first().find('a');
  var val = this.value;
  if(!val || val.slice(-1)=='/') {
    $a.removeAttr('href');
  } else {
    var add = '.json';
    var len = add.length;
    while(len >= 0) {
      var end = val.slice(-len);
      if(len == 0 || end == add.slice(0,len)){
        val += add.slice(len);
        break;
      }
      --len;
    }
    $a.attr('href','../texts.php#verses/~/' + val);
  }
  $('#imgf_' + this.id + ',#pdff_' + this.id).val(val);
  $(this).data('value',val);
}

function updateGenre(e,ui) {
  $('#imgf_' + this.id + ',#pdff_' + this.id).add(this).val(ui.item.value);
  var section = $(this).parents('tr').attr('section') || '';
  var checked = false;
  switch(ui.item.value) {
    case 'COMMUNION ANTIPHON':
    case 'COMMUNION CHANT':
    case 'ENTRANCE ANTIPHON':
    case 'ENTRANCE CHANT':
      checked = true;
      break;
  }
  $('#cbGloryBe_'+section).attr('checked',checked).trigger('change');
  checkAlleluiaSectionName(section);
}

function clearFields(){
  $('input:not(.donotclear):not([type=radio]),select').val('');
  $('input[name=includeverses]').val('1');
  $('input[type=checkbox]:not(.donotclear)').prop('checked',false).change();
  $('#rbMarginalNumbers12pt,#rbMarginalNumbersAlignGenre').prop('checked',true).change();
  $('#btnAntiphonOnly').prop('disabled',false).button('refresh');
  $('a.del-section').click();
  $('#imgf_txtOverrideTextLeft,#pdff_txtOverrideTextLeft,#imgf_txtOverrideTextRight,#pdff_txtOverrideTextRight,#imgf_txtOverrideHeader,#pdff_txtOverrideHeader').val('null');
  numSections = 0;
  sectionType = [];
  numVerses = [];
  numEngravings = [];
  lstSectionID = {};
  lstEngraving = {};
  lstEngravingName = {};
  lstPsalmTone = {};
  lstPsalmToneInfo = {};
  lstVerseSource = {};
  lstVerseEdition = {};
  addToEngraving = {};
  $("#txtFooter").val('www.illuminarepublications.com.txt').keyup();
  checkFooter();
}
var numSections = 0;
var sectionType = [];
var numVerses = [];
var numEngravings = [];
var lstTitle = '';
var lstSubtitle = '';
var lstSupertitle = '';
var lstSectionID = {};
var lstEngraving = {};
var lstEngravingName = {};
var lstPsalmTone = {};
var lstPsalmToneInfo = {};
var lstVerseSource = {};
var lstVerseEdition = {};

var addToEngraving = {};
function addToEngravingChanged(e) {
  var $this = $(this);
  var section = $this.parents('tr').attr('section') || '';
  $elem = $('#imgf_' + this.id + ',#pdff_' + this.id);
  $elem.val(this.value);
}

function sigliaChanged(e){
  var section = $(this).parents('tr').attr('section') || '';
  var $siglia = $('[id^=cbSiglia][id$=_' + section + ']');
  var siglia = [];
  $siglia.each(function(){
    if(this.checked) siglia.push(this.value);
  });
  $('[id$=siglia_' + section + ']').val(siglia.join(', '));
}

function sigliaOverrideChanged(e){
  var $siglia = $('[id^=cbOverrideSiglia]');
  var siglia = [];
  $siglia.each(function(){
    if(this.checked) siglia.push(this.id.match(/^cbOverrideSiglia(.*)$/)[1]);
  });
  $('[id$=overrideSiglia]').val(siglia.join(', '));
}

function selectGenreQualifier(e,ui) {
  $('#imgf_' + this.id + ',#pdff_' + this.id).val(ui.item.value);
}

function selectLoadScore(e,ui) {
  var $this = $(this);
  var value = ui.item.value;
  if(value.slice(-1)=='/'){
    $this.autocomplete('search',value);
  } else {
    loadDoc(value);
  }
}

function selectSectionID(e,ui) {
  var $this = $(this);
  var $tr = $this.parents('tr');
  var section = $tr.attr('section') || '';
  var type = sectionType[section];
  var sectionID = (ui && ui.item.value) || this.value;
  if(e.type=='keyup' && sectionID == '' && $('table[section='+section+'].main [id^=txtEngraving_]').val()){
    $('#createSection_'+section).button('enable');
  }
  if(sectionID.slice(-1)=='/'){
    if(ui) $this.autocomplete('search',sectionID);
  } else {
    if(e.type=='autocompleteselect') $('#createSection_'+section).button('disable');
    if(sectionID.match(/^gospel-verses\/|(?:\/(\d+)|(?:alleluia|vbg)(?:_[ivx]+)?)$/) && sectionID != lstSectionID[section]){
      lstSectionID[section] = sectionID;
      var type = sectionType[section].match(/(Modern|Square|text)$/);
      if(type) {
        type = type[1];
      } else {
        type = 'Square';
      }
      $.ajax({
        url: '../get.php?file='+(type=='text'?'text-sections/':'engraving-sections/'+type.toLowerCase()+'/') + sectionID + '.json',
        dataType: 'json',
        cache: false,
        success: function(data,status,jqXHR){
          loadSection(data,section,null,true);
          hideAllVerseSubsections(section);
          hideAllEngravingSubsections(section);
          $this.focus();
        },
        error: function(jqXHR,status,error){
          console.warn(error);
        }
      });
    }
  }
}

function updateFooterText(e,ui) {
  checkFooter(ui.item.value);
}

function checkFooter(pName) {
  var name = pName || $('#txtFooter').val();
  var $label = $($('#txtFooter').prop('labels')),
      $anchors = $label.find('a');
  if(name.length == 0) {
    $anchors.attr('href',null);
    $('[id$=txtFooter]').val(null);
    return;
  }
  if(!name.match(/\.txt$/)) {
    name += '.txt';
  }
  $anchors.attr('href','../texts.php#footers/' + name);
  $('[id$=txtFooter]').val(name);
}

function updateTemplateLink(pName) {
  var name = typeof(pName)==='string'? pName : $('#txtTemplate').val(),
      $anchors = $($('#txtTemplate').prop('labels')).find('a');
  if(name.length == 0) {
    name = 'default.json';
  }
  $anchors.attr('href','../texts.php#score-templates/' + name);
}

function updateReference(e,ui) {
  var $this = $(this);
  var $tr = $this.parents('tr');
  var section = $tr.attr('section') || '';
  var text = ui.item.value;
  if(text.match(/\/$/)){
    $this.autocomplete('search');
    return;
  }
  lstEngravingName[section] = text;
  $("[id$=txtEngraving_" + section + "]").val(text);
  checkReferenceText(text,section)
}

function checkReferenceText(text,section){
  var $sectionID = $('#sectionID_' + section);
  var enableButton = 'disable';
  var sectionDir = text.match(/\.txt$/)?text.slice(0,-4) : text;
  sectionDir += '/';
  if($sectionID.length && ($sectionID.val().indexOf(sectionDir)<0 || !$sectionID.val().match(/\/\d+$/))) {
    enableButton = 'enable';
    $('[id$=sectionID_' + section + ']').val('');
    $sectionID.val(sectionDir);
  }
  $sectionID.autocomplete('close');
  $($("#txtEngraving_" + section).prop('labels')).find('a').attr('href',text.length<=4?null : ('../texts.php#texts/' + text));
  $.ajax({
    url: '../get.php?file=texts/' + text,
    success: function(data){
      if(enableButton=='enable') $sectionID.autocomplete('search',sectionDir);
    },
    complete: function(jqXHR, status){
      $('#createSection_'+section).button(enableButton);
    }
  });
}

function txtFooterKeyUp(e){
  checkFooter();
}
function txtEngravingKeyUp(e){
  var $this = $(this);
  var $tr = $this.parents('tr[section]');
  var section = $tr.attr('section') || '';
  if(sectionType[section]=='text'){
    var text = $this.val();
    if(!text.match(/\.txt$/)) text += '.txt';
    lstEngravingName[section] = text;
    checkReferenceText(text,section);
  } else if(sectionType[section]=='antiphon-tone') {
    var text = $this.val();
    if(text && !text.match(/\.json$/)) text += '.json';
    $('input[type=hidden][name="engraving[]"][section='+section+']').val(text);
    $($("#txtEngraving_" + section).prop('labels')).find('a').attr('href',text.length<=4?null : ('../texts.php#texts/antiphons/' + text));
  } else if(sectionType[section]!='hymn' && !$('#txtGenre_'+section).val().match(regexAlleluiaGenre) && $this.val() !== lstEngravingName[section]) {
    $('#createSection_' + section).button('disable');
  }
}
var regexAlleluiaGenre = /(alleluia)|(verse before the gospel)/i;
function updateScore(e,ui) {
  var $this = $(this);
  var $tr = $this.parents('tr').first();
  var section = $this.parents('[section]').attr('section') || '';
  var $engraving = (this.name=='engraving')? $(this) : $('table.main.section'+section+' [name=engraving]');
  var $psalmTone = $('#selPsalmTone_'+section);
  var engraving = (this == $engraving[0] && ((ui && ui.item.value) || this.value));
  var psalmTone = (this == $psalmTone[0] && ((ui && ui.item.value) || this.value));
  var mainEngraving = $this.parents('table.main').length > 0;
  var engravingType = sectionType[section].match(/Modern$/)? 'modern' : 'square';
  if(sectionType[section] == 'hymn') {
    engravingType = 'modern';
  }
  if(engraving) {
    $('a',$tr).attr('href','../engraver#'+engravingType+'/' + engraving);
    if(engraving.slice(-1)=='/') {
      $engraving.autocomplete('search',engraving);
    } else {
      $('#pdff_txtEngraving_' + section + ',#imgf_txtEngraving_' + section).val(engraving);
      if(sectionType[section] == 'hymn')return;
      if(!mainEngraving) return;
      lstEngravingName[section] = engraving;
      if($('#txtGenre_'+section).val().match(regexAlleluiaGenre)) {
        return;
      }
      var sectionDir = engraving.match(/\.(?:gabc|json)$/)?engraving.slice(0,-5) : engraving;
      sectionDir += '/';
      var $sectionID = $('#sectionID_' + section);
      var enableButton = 'disable';
      if($sectionID.val().indexOf(sectionDir)<0) {
        enableButton = 'enable';
        $('[id$=sectionID_' + section + ']').val('');
        $sectionID.val(sectionDir);
        $sectionID.autocomplete('search',sectionDir);
      }
      if(sectionType[section].match(/Modern$/)) {
        $.ajax({
          url:'../get.php?file=engravings/modern/' + engraving,
          cache:false,
          success: function(data) {
            lstEngraving[section] = data
            if(!$('#txtGenre_'+section).val().match(regexAlleluiaGenre)) {
              $('#createSection_' + section).button(enableButton);
            }
          }
        });
      } else {
        $.ajax({
          url:'../get.php?file=engravings/square/' + engraving,
          cache:false,
          success: function(data) {
            data = data.replace(/\s+$/,'');
            var header = getHeader(data);
            
            delete header.cValues.spacing;
            delete header.cValues.width;
            delete header.cValues.height;
            data = header + data.slice(header.original.length);
            if(!$('#txtGenre_'+section).val().match(regexAlleluiaGenre)) {
              $('#createSection_' + section).button(enableButton);
            }
          }
        });
      }
    }
  }
  $psalmTone.parents('tr').first().find('a').attr('href',psalmTone?'../engraver#'+engravingType+'/'+psalmTone:null);
  if(psalmTone) {
    $('#pdff_selPsalmTone_' + section + ',#imgf_selPsalmTone_' + section).val(psalmTone);
    if(psalmTone.indexOf('/')<0)psalmTone = 'psalm-tones/' + psalmTone;
    $.get('../get.php?file=engravings/'+engravingType+'/' + psalmTone, function(data) {
      if(engravingType == 'modern') {
        if(data.sop) lstPsalmToneInfo[section] = getPsalmToneInfo(data);
      } else {
        data = data.slice(getHeaderLen(data)).replace(/\s+$/,'');
        psalmToneInfo = getPsalmToneInfo(data);
        lstPsalmToneInfo[section] = getPsalmToneInfo(data);
      }
    });
  }
}
var regexToneInfo = /[a-m]r((?:[^a-mr\n:;,]+[a-mxy]+(?!r))+)/g;
var regexToneCount = /[^a-mr\n]+[a-mxy]+/g;
var regexToneInfoLy = /(?:(?:\\rightBracket|Maxima|\\mediant|Maior)\s*(?:s\d+\s*)?\\recit.*?\\acute\s+)([a-g]\S*(.*?))(?=$|\\divisio|\\finalis|\\acute)/g;
var regexToneCountLy = /(\\[a-z]+)?([a-g](?:[ei]s){0,2}|[rs])([,\']*)((128|16|1|2|4|8|32|64)(\.{1,2})?(?:\*(\d+)(?:\/(\d+))?)?)?(\\[a-z]+)?/gi;
var getPsalmToneInfo = function(gabc) {
  var result = [];
  regexToneInfo.exec('');
  regexToneCount.exec('');
  var match;
  while(match = regexToneInfo.exec(gabc)) {
    result.push( match[1].match(regexToneCount).length - 1 );
  }
  return result;
}

var getPsalmToneInfoLy = function(ly) {
  var result = [];
  regexToneInfoLy.exec('');
  regexToneCountLy.exec('');
  var match;
  while(match = regexToneInfoLy.exec(ly)) {
    var m = match[1].match(regexToneCountLy);
    result.push( m? (m.length - 1) : 0 );
  }
  return result;
}

function gloryBeChanged(e) {
  $('#imgf_' + this.id + ',#pdff_' + this.id).val(this.checked?1:0);
  var $table = $(this).parents('table[section]');
  var section = $table.attr('section');
  var verse = $table.attr('verse');
  var sectionVerse = section + '_' + verse;
  if($('#cbPsalmIntact_' + section).prop('checked')) {
    updatePsalmText.apply(this,[e]);
  } else {
    var $psalmVerse = $('#txtPsalmVerse_' + sectionVerse);
    if(this.checked) {
      $psalmVerse.val( $psalmVerse.val().replace(/\s+$/,'') + '\n\n' + gloryBe(lstPsalmToneInfo[section])).trigger('autosize.resize');
    } else {
      var val = $psalmVerse.val();
      var index = indexOfGloryBe(val);
      if(index>=0) {
        $psalmVerse.val(val.slice(0,index).replace(/\s+$/g,'')).trigger('autosize.resize');
      }
    }
  }
}

function psalmIntactChanged(e) {
  if(e.originalEvent === undefined) return;
  var $table = $(this).parents('table[section]');
  var section = $table.attr('section');
  var verse = $table.attr('verse');
  var sectionVerse = section + '_' + verse;
  if(this.checked) {
    if(typeof($("#txtPsalmVerse_" + sectionVerse).data('original'))=='undefined'){
      this.checked = false; return;
    }
  } else {
    this.checked = true; return;
  }
  updatePsalmText.apply(this,[e]);
}

var gloryBeText = 'Glo+ry be to the Fa+ther, and to the |Son|, *\n  and to the Ho+ly |Spir|it.\nAs it was in the be+gin+ning, is now, and ev+er shall |be|, *\n  world with+out end. A|men|.';
var gloryBeTextNoWhitespace = 'GlorybetotheFather,andtotheSon,*andtotheHolySpirit.Asitwasinthebeginning,isnow,andevershallbe,*worldwithoutend.Amen.';
function gloryBe(psalmToneInfo) {
  var ms = (psalmToneInfo && psalmToneInfo[0]) || 0;
  var ts = (psalmToneInfo && psalmToneInfo[1]) || 0;
  var regex = [
    ms && new RegExp('([ +-])((?:[ +-]?[^ +-]+){'+ms+'})(?=[ +-]?\\|[^|\\n]+\\|[^|*]*\\*)'),
    ts && new RegExp('([ +-])((?:[ +-]?[^ +-]+){'+ts+'})(?=[ +-]?\\|[^|\\n]+\\|[^|*]*(?:\\n|$))')
  ];
  var lines = gloryBeText.split('\n');
  $.each(lines,function(i){
    if(regex[i%2]) lines[i] = this.replace(regex[i%2],'$1_$2_');
  });
  return lines.join('\n').replace(/\+/g,'');
}

function updatePsalmText(e) {
  var $table = $(this).parents('table[section]');
  var section = $table.attr('section');
  var verse = $table.attr('verse');
  var sectionVerse = section + '_' + verse;
  var glorybe = $('#cbGloryBe_' + sectionVerse)[0].checked;
  var psalmToneInfo = lstPsalmToneInfo[section];
  if(!$("#cbPsalmIntact_"+sectionVerse).prop('checked') && $("#txtPsalmVerse_" + sectionVerse).val().length) {
    return;
  }
  var data = {glorybe: glorybe? 1 : 0};
  if(psalmToneInfo) {
    data.ms = psalmToneInfo[0] || 0;
    data.ts = psalmToneInfo[1] || 0;
  }
  var edition = lstVerseEdition[sectionVerse];
  if(edition=='~') {
    edition += '/' + $('#pdff_txtVerseFile_' + sectionVerse).val();
  } else {
    var verseSource = '';
    var title = data.title = $('#txtPsalmTitle_' + sectionVerse).val();
    var match = title.match(/([\w-]+\.?)\s+(\d+).*/);
    if(match) verseSource = getVerseSource(match[1]);
    if(!match || !verseSource) return;
    data.source = verseSource;
  }
  data.edition = edition;
  data.keepVerseNumbers = 1;
  $.get('../psalmref.php', data, function(data) {
    if(data && data.text) {
      if(data.title && data.title.length > 0) {
        $('#txtPsalmTitle_' + sectionVerse).val(data.title).change();
      }
      data = data.text;
    }
    if(typeof(data)=='string' && data.length > 0) {
      data = data.replace(/^\s+|\s+$/g,'');
      var $psalmVerse = $("#txtPsalmVerse_" + sectionVerse);
      $("#cbPsalmIntact_" + sectionVerse).attr('checked',true);
      $psalmVerse.val(data).data({original:$psalmVerse.val()}).attr('title','').trigger('autosize.resize');
      setDefaultNumberVersesIfChanged.apply($psalmVerse[0],[e]);
    }
  });
}

function checkAlleluiaSectionName(section){
  var genre = $('#txtGenre_'+section).val();
  var match = genre.match(regexAlleluiaGenre);
  var gabc = lstEngraving[section];
  var annotation;
  if(sectionType[section]=='engraving-Square') {
    var header = getHeader(gabc||'');
    annotation = header.annotation;
  }
  var title = $('#txtTitle').val();
  $('tr.section'+section+'.overrideFilename').toggle(match?true:false).toggleClass('hidden',match?false:true);
  if(match) {
    $.getJSON('../shortname.php?for=' + encodeURIComponent(title),function(data){
      if(!data.shortname) {
        //TODO: need to prompt.
        //TEMP: use long name;
        data.shortname = getFilename();
      }
      var sectionName = data.shortname;
      sectionName += (match[1]? '_alleluia' : '_vbg');
      if(annotation) {
        sectionName += '_' + annotation.toLowerCase();
      }
      var candidateFilename = 'gospel-verses/' + sectionName;
      var $sectionID = $('#sectionID_'+section);
      if(!$sectionID.val().match(/_(?:alleluia|vbg)(?:_[ivx]+)?$/)) {
        $('[id$=sectionID_' + section + ']').val('');
        $sectionID.val(candidateFilename);
        $('#createSection_'+section).button('enable');
      }
    });
  } else {
    var elem = $('table.main.section'+section+' [name=engraving]').get(0);
    if(elem) updateScore.apply(elem);
  }
}

function keyDownUpdatePsalmText(e) {
  if(e.which == 13) updatePsalmText.apply(this,[e]);
}
var accentMap = {'a':'á',
 'e':'é',
 'i':'í',
 'o':'ó',
 'u':'ú',
 'y':'ý',
 'A':'Á',
 'E':'É',
 'I':'Í',
 'O':'Ó',
 'U':'Ú',
 'Y':'Ý'};
function keyUpPsalmTitle(e,keepHidden) {
  var $this = $(this);
  var $table = $(this).parents('table[section]');
  var section = $table.attr('section');
  var verse = $table.attr('verse');
  var sectionVerse = section + '_' + verse;
  var match = this.value && this.value.match(/([\w-]+\.?)\s+(\d+)/);
  var verseSource = '';
  if(match) verseSource = getVerseSource(match[1]);
  if(verseSource != lstVerseSource[sectionVerse]){
    lstVerseSource[sectionVerse] = verseSource;
    setVerseEditions($("#selVerseSource_"+sectionVerse),verseSource,sectionVerse);
  }
  var verseEdition = lstVerseEdition[sectionVerse];
  if(!match || !verseSource) {
    $this.parents('tr').first().find('a').removeAttr('href');
    $this.removeData();
    $this.siblings('.psalmPreview').fadeOut(300);
  } else if(match[2] != $this.data('psalmNum')) {
    $this.parents('tr').first().find('a').attr('href','../texts.php#verses/' + verseSource + '/' + verseEdition + '/' + match[2] + '.txt');
    
    $this.data('psalmNum', match[2]);
    $.get('../get.php?file=verses/' + verseSource + '/' + verseEdition + '/' + match[2] + '.txt',function(data){
      data = replaceEscapedDiacritics(data.replace(/\+/g,'').replace(/\|([^|]+)\|/g,'<i>$1</i>').replace(/\n/g,'<br/>').replace(/\\'([aeiouy])/ig,function(s,a){return accentMap[a];}));
      $this.data('psalmText',data);
      var $preview = $this.siblings('.psalmPreview').html('<span><b>' + verseSource + ' ' + match[2] + '</b><br/>' + data + '</span>');
      if(!keepHidden) {
        sizePsalmPreview($preview);
        $preview.fadeIn(300);
      }
    });
  }
  var psalmTitle = this.value.replace(/^([^|:]+)\:/,'|$1|:');
  if(psalmTitle != this.value) {
    var selStart = this.selectionStart + 2;
    var selEnd = this.selectionEnd + 2;
    
    this.value = psalmTitle;
    
    this.selectionStart = selStart;
    this.selectionEnd = selEnd;
  }
}
function sizePsalmPreview($preview) {
  var scrollTop = $preview.parents('div.body').scrollTop();
  var $this = $preview.siblings('input');
  var hidden = $preview.is(':hidden');
  $preview.show();
  $preview.height(
    Math.min(Math.max(100,$this.position().top - $preview.parents('div.body').position().top), $preview.children().first().height())
  );
  $preview.position({
    my: "bottom",
    at: "top",
    of: $this,
    collision: "none"
  });
  var top = parseFloat($preview.css('top'));
  top -= scrollTop
  if(top < 0) {
    $preview.height(500+top);
    $preview.css('top',scrollTop);
  }
  if(hidden) {
    $preview.hide();
  }
}
function focusInPsalmTitle(e) {
  var $this = $(this);
  var $preview = $this.siblings('.psalmPreview');
  $preview.width($this.width());
  var hidden = $preview.is(':hidden');
  sizePsalmPreview($preview);
  if(hidden && $this.data('psalmText')) {
    $preview.fadeIn(300);
  }
}
function focusOutPsalmTitle(e) {
  var $preview = $(this).siblings('.psalmPreview');
  if($preview.has(':focus').length) return;
  $preview.fadeOut(300);
}

function autocompleteKeyDown(e) {
  // if delete pressed
  if(e.which == 46) {
    var $this = $(this);
    var source = $this.autocomplete("option","source");
    var hover = $this.autocomplete("widget").find('.ui-state-hover');
    if(hover.length == 0) {
      $this.removeData('hover');
      return;
    }
    var hover = hover.text();
    if($this.data('hover') == hover) {
      //console.info('Second Time: ' + hover);
      $.get(source, {remove: hover}, function(data){
        $this.autocomplete("search");
      });
    } else {
      $this.data('hover',hover);
      //console.info('First time: ' + hover);
    }
  }
}
var activeSection;
var hideAllSections=function(i){
  $('tr[section]').removeClass('active');
  $('tr[section='+i+']').addClass('active');
};
var showSection=function(i){
  $('tr.section'+i).addClass('active');
  hideAllVerseSubsections(i);
  hideAllEngravingSubsections(i);
  activeSection = parseInt(i);
}
var hideAllVerseSubsections=function(s,v){
  $('table[section][verse]:not([section='+s+'][verse='+v+']) tr:not(.separator,.verselabel)').hide();
};
var showVerseSubsection=function(s,v){
  $('table.section'+s+'.verse'+v+' tr:not(.keephidden,.hidden)').show();
}
var hideAllEngravingSubsections=function(s,e){
  $('table[section][engraving]:not([section='+s+'][engraving='+e+']) tr:not(.separator,.engravinglabel)').hide();
}
var showEngravingSubsection=function(s,e){
  $('table.section'+s+'.engraving'+e+' tr').show();
}
function createNewSection(e) {
  var $this = $(this);
  var $tr = $this.parents('tr');
  var section = $tr.attr('section') || '';
  var type = sectionType[section];
  
  var sectionData;
  switch(type.match(/^(\w+)(?:-|$)/)[1]) {
    case 'text': 
      sectionData = {
        sectionType: 'text',
        genre: $('#txtGenre_' + section).val(),
        engraving: $('#txtEngraving_'+section).val()
      };
      break;
    case 'rubric':
      //Nothing to do.
      break;
    case 'hymn':
      sectionData = {
        sectionType: 'hymn',
        engraving: $('#txtEngraving_'+section).val()
      };
      break;
    case 'engraving':
    default:
      sectionData = {
        sectionType: $('#pdff_sectionType_' + section).val(),
        genre: $('#txtGenre_' + section).val(),
        engraving: JSON.stringify(jsonForSectionEngravings(section)),
        verses: JSON.stringify(jsonForSectionVerses(section)),
        addtoengraving: $("#selAddToEngraving_"+section).val(),
        psalmtone: $('#selPsalmTone_'+section).val(),
        spacing: $("#selSpacing_"+section).val(),
        overrideFilename: $("#txtOverrideFilename_"+section).val(),
        "_title": $('#txtTitle').val(),
        "_super": $('#txtSupertitle').val(),
        "_sub": $('#txtSubtitle').val()
      };
      break;
  }
  var $post = $.post('../getSectionID.php',sectionData,function(data,status,jqXHR){
    $('#createSection_'+section).button('disable');
    $('[id$=sectionID_' + section + ']').val(data).autocomplete('close');
    if(typeof(e)=='function') e();
  });
}
function setAutoCompletes($elem,autocompletes,usePlaceholder) {
  var src = autocompletes;
  if(!autocompletes) {
    autocompletes = [];
    src = null;
  } else if(typeof(autocompletes)=='string') {
    src = autocompletes = [autocompletes];
  }
  $elem.autocomplete('option',{source: src});
  if(usePlaceholder && autocompletes.length > 0 && autocompletes.indexOf($elem.val()) < 0) $elem.val('');
  if(autocompletes.length == 1) {
    if(autocompletes[0]) $elem.val(autocompletes[0]).change();
  } else if(autocompletes.length == 0 || !usePlaceholder) {
    $elem.attr('placeholder','');
  } else if(autocompletes.length > 1 && autocompletes.indexOf('')<0 && usePlaceholder) {
    $elem.attr('placeholder','Pick One...');
  }
}
function titleChanged(e,ui){
  var $this = $(this);
  if(ui) {
    $this.val(ui.item.value).change();
    return;
  }
  var $super = $('#txtSupertitle');
  var $sub = $('#txtSubtitle');
  var superVal = $super.val();
  var subVal = $sub.val();
  var val = $this.val().replace(/\s*\\\\\s*/g,' ');
  if(val == lstTitle) return;
  lstTitle = val;
  
  if(liturgy.titles.indexOf(val) >= 0) {
    var subtitles = liturgy.mapTitleSubtitle[val];
    var supertitles = liturgy.mapTitleSupertitle[val];
    if(superVal) subtitles = liturgy.mapTitleSuperSub[[val,superVal]];
    if(subVal) supertitles = liturgy.mapTitleSubSuper[[val,subVal]];
    setAutoCompletes($super,supertitles,true);
    setAutoCompletes($sub,subtitles,true);
  } else {
    setAutoCompletes($super,liturgy.dates,false);
    setAutoCompletes($sub,liturgy.secondaryTitles,false);
  }
  updateFilename();
}
function subtitleChanged(e,ui){
  var $sub = $(this);
  if(ui) {
    $sub.val(ui.item.value).change();
    return;
  }
  var $super = $('#txtSupertitle');
  var $title = $('#txtTitle');
  var superVal = $super.val();
  var subVal = ui? ui.item.value : $sub.val();
  var val = $title.val();
  if(subVal == lstSubtitle) return;
  lstSubtitle = subVal;
  
  if(liturgy.titles.indexOf(val) >= 0) {
    var subtitles = liturgy.mapTitleSubtitle[val];
    if(subtitles && (typeof(subtitles)=='string') || subtitles.indexOf(subVal) >= 0) {
      var supertitles = liturgy.mapTitleSubSuper[[val,subVal]];
      setAutoCompletes($super,supertitles,true);
    } else {
      setAutoCompletes($super,liturgy.mapTitleSupertitle[val],false);
    }
  }
  updateFilename();
}
function supertitleChanged(e,ui){
  var $super = $(this);
  if(ui) {
    $super.val(ui.item.value).change();
    return;
  }
  var $title = $('#txtTitle');
  var $sub = $('#txtSubtitle');
  var superVal = ui? ui.item.value : $super.val();
  var subVal = $sub.val();
  var val = $title.val();
  if(superVal == lstSupertitle) return;
  lstSupertitle = superVal;
  
  if(liturgy.dates.indexOf(superVal) >= 0) {
    var titles = liturgy.mapSuperTitle[superVal];
    if(typeof(titles)=='string') {
      if($title.val() == '') {
        $title.val(val = titles).change();
      }
    } else if(val.length > 0 && titles.indexOf(val) < 0) {
      $title.val(val = '').change();
    }
  }
  if(liturgy.titles.indexOf(val) >= 0) {
    var supertitles = liturgy.mapTitleSupertitle[val];
    if(supertitles && (typeof(supertitles)=='string') || supertitles.indexOf(superVal) >= 0) {
      var subtitles = liturgy.mapTitleSuperSub[[val,superVal]];
      setAutoCompletes($sub,subtitles,true);
    } else {
      setAutoCompletes($sub,liturgy.mapTitleSubtitle[val],false);
    }
  }
  updateFilename();
}
function updateFilename(e){
  var $filename = $('#txtFilename');
  if($filename.attr('disabled')) {
    $filename.val(getFilename());
  }
};
function getFilename(){
  return getFilenameForTitleSuperSub($('#txtTitle').val(),$('#txtSupertitle').val(),$('#txtSubtitle').val());
}
function getFilenameForTitleSuperSub(title,superval,subval){
  title = title.replace(/\s*\\\\\s*/g,' ');
  var result = liturgy.mapTitleSuperSubShortname[[title,superval,subval]];
  return result || title.toLowerCase().replace(/'|\W+$/g,'').replace(/\W+/g,'-');
}
var verseEditions = null;
var verseEditionNames = {'rgp':'Revised Grail Psalter'};
var getVerseSource = function(src){
  if(src=='Psalm' || src == 'Ps.') return 'Psalm';
  if(!verseEditions) return src;
  if(src in verseEditions) {
    return src;
  }
  if(src.slice(-1)=='.') {
    src = src.slice(0,-1);
    for(source in verseEditions){
      if(source.indexOf(src)==0){
        return source;
      }
    }
  }
}
function verseEditionChanged(e){
  var $table = $(this).parents('table[section]');
  var section = $table.attr('section');
  var verse = $table.attr('verse');
  var sectionVerse = section + '_' + verse;
  var verseEdition = this.value;
  var $verseFileRow = $('table[section='+section+'][verse='+verse+'] tr.versefile');
  if(verseEdition=='~') {
    $verseFileRow.show().removeClass('keephidden');
  } else {
    $verseFileRow.hide().addClass('keephidden');
    updatePsalmText.apply($('#txtPsalmTitle_'+sectionVerse)[0],[e]);
  }
  $('#imgf_' + this.id + ',#pdff_' + this.id).val(verseEdition);
}
function setVerseEditions($sel,verseSource,sectionVerse){
  if(!verseEditions)return;
  var selected = $sel.prop('value');
  var editions = verseEditions[verseSource];
  var i;
  if(!editions){
    editions = [];
  }
  var selectedI = editions.indexOf(selected);
  var changed = false;
  if(selectedI<0){
    selectedI = 0;
    selected = editions[0] || '~';
    changed = true;
  }
  lstVerseEdition[sectionVerse] = selected;
  var editionHtml=[];
  for(i in editions){
    var e = editions[i];
    var name = (e in verseEditionNames)? verseEditionNames[e] : e;
    editionHtml.push('<option value="'+e+'"'+(i==selectedI?' selected':'')+'>'+name+'</option>');
  }
  editionHtml.push('<option value="~"'+(selected=='~'?' selected':'')+'>Load verse from file...</option>');
  $editions = $(editionHtml.join(''));
  $sel.empty().append($editions);
  if(changed) $sel.change();
}
$(function() {
  $.ajaxSetup({cache:false});
  var onFocus=function(e){
    var $tr = $(this).parents('tr[section],table[section]').first();
    var section = $tr.attr('section');
    if(section) {
      if(e.type=='click'){
        var $trSub = $(e.srcElement).parents('tr').first();
        if($trSub.is('.placeholder')) {
          do {
            var $input = $trSub.find('input,select,textarea').first();
            if($input.length) {
              hideAllSections(section);
              $input.focus();
              return;
            }
            $trSub = $trSub.next();
          } while($trSub.length)
        }
        if($(e.srcElement).is('a,hr,span,input,select,textarea,label,.separator') ||
           $tr.has('table').length) {
          return;
        } else {
          var $input = $tr.find('input,select,textarea').first();
          if($input.length) {
            hideAllSections(section);
            $input.focus();
            return;
          }
        }
      }
      hideAllSections(section);
      showSection(section);
      var $verseSubsection = $(this).parents('table[verse]');
      if($verseSubsection.length>0) {
        var verse = $verseSubsection.attr('verse');
        hideAllVerseSubsections(section,verse);
        showVerseSubsection(section,verse);
        return;
      }
      var $engravingSubsection = $(this).parents('table[engraving]');
      if($engravingSubsection.length>0) {
        var engraving = $engravingSubsection.attr('engraving');
        hideAllEngravingSubsections(section,engraving);
        showEngravingSubsection(section,engraving);
      }
    }
  };
  var sectionSeparatorHtml = '<tr class="buttonrow"><td colspan="2"><hr/><ul class="menu" style="width:100px;float:left">\
    <li>\
      <a href="#">+</a>\
      <ul>\
        <li><a href="#">Engraving Section</a>\
            <ul>\
              <li><a class="add-section" type="engraving-Square" href="#">Square</a></li>\
              <li><a class="add-section" type="engraving-Modern" href="#">Modern</a></li>\
            </ul>\
        </li>\
        <li><a class="add-section" type="text" href="#">Text Section</a></li>\
        <li><a class="add-section" type="antiphon-tone" href="#">Antiphon Tone Section</a></li>\
        <li><a class="add-section" type="rubric" href="#">Rubric Section</a></li>\
        <li><a class="add-section" type="hymn" href="#">Hymn Section</a></li>\
        <li><a class="add-section" type="hairline" href="#">Hairline Section</a></li>\
        <li><a class="add-section" type="pagebreak" href="#">Page Break Section</a></li>\
        <li><a class="add-section" type="space" href="#">Space Section</a></li>\
      </ul>\
    </li>\
  </ul>\
  </td></tr>\
<tr class="separator"><td colspan="2"><hr/></td></tr>';
  var addVerseMenuHtml = '<li><a href="#">+</a>\
  <ul>\
    <li><a class="add-verse" href="#">Verse</a></li>\
    <li><a class="add-verse" type="rubric" href="#">Rubric</a></li>\
    <li><a class="add-verse" type="space" href="#">Space</a></li>\
  </ul></li>';
  var verseGroupBeginningHtml = '<table style="width:100%;padding-top:0;padding-bottom:0"><tr><td colspan="2" class="placeholder" style="display:none"></td>\
  </tr><tr class="buttonrow"><td colspan="2"><hr class="verse"/><ul class="menu">'+addVerseMenuHtml+'</ul></td></tr>\
<tr class="verse separator"><td colspan="2"><hr class="verse"/></td></tr>';
  var verseGroupEndingHtml = '</table>';
  var singleVerseHtml = verseGroupBeginningHtml + '<tr class="verselabel">\
    <td><label for="txtVerseLabel"><a tabindex="-1" target="_blank" href="../texts.php#autocompletes/verselabel.txt">Verse Label</a></label></td>\
    <td><a tabindex="-1" class="remove-button del-verse" href="#"></a><div style="margin-right:24px"><input type="text" id="txtVerseLabel" name="verselabel"/></div></td>\
</tr><tr>\
    <td><label for="cbPageBreakBeforeVerse">Page Break Before</label></td>\
    <td><input type="checkbox" id="cbPageBreakBeforeVerse" name="pagebreakbeforeverse"/></td>\
</tr><tr class="versetitle">\
    <td><label for="txtPsalmTitle"><a tabindex="-1" target="_blank">Verse Title</a></label></td>\
    <td><input type="text" id="txtPsalmTitle" name="psalmtitle"/><div class="psalmPreview"></div></td>\
</tr><tr>\
    <td><label for="selVerseSource">Verse Source</label></td>\
    <td><div class="selectDiv"><select id="selVerseSource" name="versesource"></select></div></td>\
</tr><tr class="versefile">\
    <td><label for="txtVerseFile"><a tabindex="-1" target="_blank">Verse File Source</a></label></td>\
    <td><input type="text" id="txtVerseFile" name="versefile"/></td>\
</tr><tr>\
    <td><label for="cbPsalmIntact">Verse Unchanged</label></td>\
    <td><input type="checkbox" tabindex="-1" id="cbPsalmIntact" checked /></td>\
</tr><tr>\
    <td><label for="txtPsalmVerse">Verse</label></td>\
    <td><textarea class="engraving" style="width:100%" id="txtPsalmVerse" name="psalmverse"></textarea></td>\
</tr><tr>\
    <td><label>Mark verses with</label></td>\
    <td id="rbMarkVerses">\
      <input type="radio" tabindex="-1" id="rbMarkVersesNumbers" name="markverses" value="numbers"/><label for="rbMarkVersesNumbers">Numbers</label>\
      <input type="radio" tabindex="-1" id="rbMarkVersesReferenceNumbers" name="markverses" value="referenceNumbers"/><label for="rbMarkVersesReferenceNumbers">Reference Numbers</label>\
      <input type="radio" tabindex="-1" id="rbMarkVersesVersicle" name="markverses" checked value="versicle"/><label for="rbMarkVersesVersicle">&#8483;</label>\
      <input type="radio" tabindex="-1" id="rbMarkVersesNothing" name="markverses" value="nothing"/><label for="rbMarkVersesNothing">Nothing</label>\
    </td>\
</tr><tr>\
    <td><label for="cbNotateVerses">Notate Verses</label></td>\
    <td><input type="checkbox" tabindex="-1" id="cbNotateVerses" name="notateverses"/></td>\
</tr><tr>\
    <td><label for="cbMarkPenultimateAccent">Mark Penultimate Accent</label></td>\
    <td><input type="checkbox" tabindex="-1" id="cbMarkPenultimateAccent" name="markpenultimateaccent"/></td>\
</tr><tr>\
    <td><label for="cbAllowPageBreaksMidVerse">Allow Page Breaks Mid-Verse</label></td>\
    <td><input type="checkbox" tabindex="-1" id="cbAllowPageBreaksMidVerse" name="allowpagebreaksmidverse"/></td>\
</tr><tr>\
    <td><label for="cbGloryBe">Add Glory Be</label></td>\
    <td><input type="checkbox" tabindex="-1" id="cbGloryBe" name="glorybe"/></td>\
</tr>' + verseGroupEndingHtml;
  var addVerseButton = '<tr><td colspan="2" class="verses"><hr class="verse"/><ul class="menu above">'+addVerseMenuHtml+'</ul></td></tr>';
  var singleEngravingHtml = {};
  singleEngravingHtml.Square = '<table style="width:100%;padding-top:0;padding-bottom:0"><tr class="buttonrow"><td colspan="2"><hr class="engraving"/><a class="add-engraving" href="#">Add Engraving</a>\
  </td></tr>\
<tr class="engraving separator"><td colspan="2"><hr class="engraving"/></td></tr><tr class="engravinglabel"><td><label for="txtEngravingLabel"><a tabindex="-1" target="_blank" href="../texts.php#autocompletes/engravinglabel.txt">Engraving Label</a></label></td>\
    <td><a tabindex="-1" class="remove-button del-engraving" href="#"></a><div style="margin-right:24px"><input type="text" id="txtEngravingLabel" name="engravinglabel"/></div></td>\
  </tr><tr>\
    <td><label for="txtGenreNumber">Marginal Number</label></td>\
    <td><input type="text" id="txtGenreNumber" name="genrenumber" style="width:50px"/>\
    <input type="radio" id="rbGenreNumberLeft" name="genrenumberleftright" value="left" tabindex="-1" checked/><label for="rbGenreNumberLeft">Left</label>\
    <input type="radio" id="rbGenreNumberRight" name="genrenumberleftright" value="right" tabindex="-1"/><label for="rbGenreNumberRight">Right</label></td>\
</tr><tr>\
    <td><label for="selSpacing">Spacing</label></td>\
    <td><div class="selectDiv"><select id="selSpacing" name="spacing">\
      <option value="">Default</option>\
      <option value="vichi">Vichi</option>\
      <option value="smith">Smith</option>\
    </select></div></td>\
</tr><tr class="engraving">\
    <td><label for="txtEngraving"><a tabindex="-1" target="_blank">Engraving</a></label></td>\
    <td><input type="text" id="txtEngraving" name="engraving"/></td>\
</tr><tr>\
    <td></td>\
    <td><input type="checkbox" tabindex="-1" id="cbSigliaRM" value="RM" name="siglia"/><label for="cbSigliaRM">RM</label>\
        <input type="checkbox" tabindex="-1" id="cbSigliaGR" value="GR" name="siglia"/><label for="cbSigliaGR">GR</label>\
        <input type="checkbox" tabindex="-1" id="cbSigliaGS" value="GS" name="siglia"/><label for="cbSigliaGS">GS</label>\
        <input type="checkbox" tabindex="-1" id="cbSigliaL" value="L" name="siglia"/><label for="cbSigliaL">L</label>\
        <input type="checkbox" tabindex="-1" id="cbSigliaIcon-white" value="Icon-white" name="siglia"/><label for="cbSigliaIcon-white"><img class="siglia-icon" src="../library/~icons/white.png"/></label>\
        <input type="checkbox" tabindex="-1" id="cbSigliaIcon-half" value="Icon-half" name="siglia"/><label for="cbSigliaIcon-half"><img class="siglia-icon" src="../library/~icons/half.png"/></label>\
        <input type="checkbox" tabindex="-1" id="cbSigliaIcon-black" value="Icon-black" name="siglia"/><label for="cbSigliaIcon-black"><img class="siglia-icon" src="../library/~icons/black.png"/></label>\
        <input type="checkbox" tabindex="-1" id="cbSigliaIcon-asterisk" value="Icon-asterisk" name="siglia"/><label for="cbSigliaIcon-asterisk"><img class="siglia-icon" src="../library/~icons/asterisk.png"/></label>\
    </td>\
</tr><tr>\
    <td><label for="selAddToEngraving">Add to Engraving</label></td>\
    <td><div class="selectDiv"><select id="selAddToEngraving" name="addtoengraving">\
      <option selected></option>\
      <option>&lt;v>\\greblockcustos&lt;/v>(Z)</option>\
      <option>&lt;v>\\greblockcustos&lt;/v>(z)</option>\
      <option>&lt;v>\\greblockcustos&lt;/v></option>\
    </select></div></td>\
</tr><tr class="removetranslation">\
    <td><label for="cbRemoveTranslation">Hide Translation</label></td>\
    <td><input type="checkbox" tabindex="-1" id="cbRemoveTranslation" name="removetranslation"/></td>\
</tr><tr class="overridetextleft">\
    <td><input type="checkbox" id="cbOverrideTextLeft" style="display:none"/> <label for="cbOverrideTextLeft"><a tabindex="-1" class="override-text-left" target="_blank" href="../texts.php#autocompletes/overridetextleft.txt">Override Text-Left</a></label></td>\
    <td><input type="text" disabled id="txtOverrideTextLeft" name="overridetextleft"/></td>\
</tr><tr class="overridetextright">\
    <td><input type="checkbox" id="cbOverrideTextRight" style="display:none"/> <label for="cbOverrideTextRight"><a tabindex="-1" class="override-text-right" target="_blank" href="../texts.php#autocompletes/overridetextright.txt">Override Text-Right</a></label></td>\
    <td><input type="text" disabled id="txtOverrideTextRight" name="overridetextright"/></td>\
</tr><tr>\
    <td><label for="cbPageBreakBeforeEngraving">Page Break Before</label></td>\
    <td><input type="checkbox" tabindex="-1" id="cbPageBreakBeforeEngraving" name="pagebreakbeforeengraving"/></td>\
</tr><tr>\
    <td><label for="selSpaceAboveChant">Space Above Chant</label></td>\
    <td><div class="selectDiv"><select tabindex="-1" id="selSpaceAboveChant" name="spaceabovechant"><option>-3</option><option selected>0</option><option>3.9</option><option>7.8</option><option>15.6</option></select></div></td>\
</tr><tr>\
    <td><label for="selSpaceBelowChant">Space Below Chant</label></td>\
    <td><div class="selectDiv"><select tabindex="-1" id="selSpaceBelowChant" name="spacebelowchant"><option>-11.7</option><option>-7.8</option><option>-3.9</option><option>0</option><option>3.9</option><option selected>7.8</option><option>15.6</option></select></div></td>\
</tr></table>';
  singleEngravingHtml.Modern = '<table style="width:100%;padding-top:0;padding-bottom:0"><tr class="buttonrow"><td colspan="2"><hr class="engraving"/><a class="add-engraving" href="#">Add Engraving</a>\
  </td></tr>\
<tr class="engraving separator"><td colspan="2"><hr class="engraving"/></td></tr><tr class="engravinglabel"><td><label for="txtEngravingLabel"><a tabindex="-1" target="_blank" href="../texts.php#autocompletes/engravinglabel.txt">Engraving Label</a></label></td>\
    <td><a tabindex="-1" class="remove-button del-engraving" href="#"></a><div style="margin-right:24px"><input type="text" id="txtEngravingLabel" name="engravinglabel"/></div></td>\
  </tr><tr>\
    <td><label for="txtGenreNumber">Marginal Number</label></td>\
    <td><input type="text" id="txtGenreNumber" name="genrenumber" style="width:50px"/>\
    <input type="radio" id="rbGenreNumberLeft" name="genrenumberleftright" value="left" tabindex="-1" checked/><label for="rbGenreNumberLeft">Left</label>\
    <input type="radio" id="rbGenreNumberRight" name="genrenumberleftright" value="right" tabindex="-1"/><label for="rbGenreNumberRight">Right</label></td>\
</tr><tr class="engraving">\
    <td><label for="txtEngraving"><a tabindex="-1" target="_blank">Engraving</a></label></td>\
    <td><input type="text" id="txtEngraving" name="engraving"/></td>\
</tr><tr>\
    <td><label for="txtSpaceBetweenSystems">Space Between Systems</label></td>\
    <td><input type="text" id="txtSpaceBetweenSystems" name="spacebetweensystems" placeholder="(Default: 12pt plus 6pt minus 8pt)"/></td>\
</tr><tr>\
    <td></td>\
    <td><input type="checkbox" tabindex="-1" id="cbSigliaRM" value="RM" name="siglia"/><label for="cbSigliaRM">RM</label>\
        <input type="checkbox" tabindex="-1" id="cbSigliaGR" value="GR" name="siglia"/><label for="cbSigliaGR">GR</label>\
        <input type="checkbox" tabindex="-1" id="cbSigliaGS" value="GS" name="siglia"/><label for="cbSigliaGS">GS</label>\
        <input type="checkbox" tabindex="-1" id="cbSigliaL" value="L" name="siglia"/><label for="cbSigliaL">L</label>\
        <input type="checkbox" tabindex="-1" id="cbSigliaIcon-white" value="Icon-white" name="siglia"/><label for="cbSigliaIcon-white"><img class="siglia-icon" src="../library/~icons/white.png"/></label>\
        <input type="checkbox" tabindex="-1" id="cbSigliaIcon-half" value="Icon-half" name="siglia"/><label for="cbSigliaIcon-half"><img class="siglia-icon" src="../library/~icons/half.png"/></label>\
        <input type="checkbox" tabindex="-1" id="cbSigliaIcon-black" value="Icon-black" name="siglia"/><label for="cbSigliaIcon-black"><img class="siglia-icon" src="../library/~icons/black.png"/></label>\
        <input type="checkbox" tabindex="-1" id="cbSigliaIcon-asterisk" value="Icon-asterisk" name="siglia"/><label for="cbSigliaIcon-asterisk"><img class="siglia-icon" src="../library/~icons/asterisk.png"/></label>\
    </td>\
</tr><tr>\
    <td><label for="selAddToEngraving">Add to Engraving</label></td>\
    <td><div class="selectDiv"><select id="selAddToEngraving" name="addtoengraving">\
      <option selected></option>\
      <option>\\bar ""</option>\
      <option>r16</option>\
      <option>\\z</option>\
    </select></div></td>\
</tr><tr>\
    <td><label for="cbRaggedLast">Ragged Last Line</label></td>\
    <td><input type="checkbox" tabindex="-1" id="cbRaggedLast" name="raggedlast" value="t"/></td>\
</tr><tr class="overridetextleft">\
    <td><input type="checkbox" id="cbOverrideTextLeft" style="display:none"/> <label for="cbOverrideTextLeft"><a tabindex="-1" class="override-text-left" target="_blank" href="../texts.php#autocompletes/overridetextleft.txt">Override Text-Left</a></label></td>\
    <td><input type="text" disabled id="txtOverrideTextLeft" name="overridetextleft"/></td>\
</tr><tr class="overridetextright">\
    <td><input type="checkbox" id="cbOverrideTextRight" style="display:none"/> <label for="cbOverrideTextRight"><a tabindex="-1" class="override-text-right" target="_blank" href="../texts.php#autocompletes/overridetextright.txt">Override Text-Right</a></label></td>\
    <td><input type="text" disabled id="txtOverrideTextRight" name="overridetextright"/></td>\
</tr><tr>\
    <td><label for="cbPageBreakBeforeEngraving">Page Break Before</label></td>\
    <td><input type="checkbox" tabindex="-1" id="cbPageBreakBeforeEngraving" name="pagebreakbeforeengraving"/></td>\
</tr><tr>\
    <td><label for="selSpaceAboveChant">Space Above Engraving</label></td>\
    <td><div class="selectDiv"><select tabindex="-1" id="selSpaceAboveChant" name="spaceabovechant"><option>-3</option><option selected>0</option><option>3.9</option><option>7.8</option><option>15.6</option></select></div></td>\
</tr><tr>\
    <td><label for="selSpaceBelowChant">Space Below Engraving</label></td>\
    <td><div class="selectDiv"><select tabindex="-1" id="selSpaceBelowChant" name="spacebelowchant"><option>-11.7</option><option>-7.8</option><option>-3.9</option><option>0</option><option>3.9</option><option selected>7.8</option><option>15.6</option></select></div></td>\
</tr></table>';
  var sectionHtml = {
    hairline: '<tr class="title placeholder">\
<td colspan="2" style="text-align:center;text-weight:bold"><a tabindex="-1" class="remove-button del-section" href="#"></a><b>Hairline</b></td>\
</tr><tr>\
    <td><label for="txtHairlineText"><a tabindex="-1" target="_blank" href="../texts.php#autocompletes/hairlineTexts.txt">Hairline Text</a></label></td>\
    <td><input type="text" id="txtHairlineText" name="text"/></td>\
</tr><tr>\
    <td><label for="txtMargin">Width</label></td>\
    <td><select type="text" id="txtHairlineMargin" name="margin"><option value="0" selected>Full</option><option value="0.625">-1.25"</option><option value="1.5">-3"</option></select></td>\
</tr>',
    pagebreak: '<tr class="title placeholder"><td colspan="2" style="text-align:center;text-weight:bold"><a tabindex="-1" class="remove-button del-section" href="#"></a><b>Page Break</b></td></tr>',
    space: '<tr class="placeholder hidden"><td colspan="2" style="text-align:center;text-weight:bold"><a tabindex="-1" class="remove-button del-section" href="#"></a><b>Space (7.8pt)</b></td>\
    </tr><tr class="title">\
  <td><label for="selSpace">Space:</label></td>\
  <td><a tabindex="-1" class="remove-button del-section" href="#"></a><div class="selectDiv" style="margin-right:18px"><select id="selSpace" name="sectionID"><option>-23.4</option><option>-15.6</option><option>-7.8</option><option selected="true">+7.8</option><option>+15.6</option><option>+23.4</option></select></div></td>\
</tr>',
    hymn: '<tr class="engraving genre">\
    <td><label for="txtEngraving"><a tabindex="-1" target="_blank">Hymn</a></label></td>\
    <td><a tabindex="-1" class="remove-button del-section" href="#"></a><div style="margin-right:24px"><input type="text" id="txtEngraving" name="engraving"/></div></td>\
</tr><tr>\
    <td><label for="txtHymnHeader">Header</label></td>\
    <td><input type="text" id="txtHymnHeader" name="hymnHeader"/></td>\
</tr><tr>\
    <td><label for="txtHymnSupertitle">Supertitle</label></td>\
    <td><input type="text" id="txtHymnSupertitle" name="hymnsupertitle"/></td>\
</tr><tr>\
    <td><label for="txtHymnSubtitle">Subtitle</label></td>\
    <td><input type="text" id="txtHymnSubtitle" name="hymnsubtitle"/></td>\
</tr><tr>\
    <td><label for="txtNumVerses">Number of Verses with Music</label></td>\
    <td><input type="text" id="txtNumVerses" name="numverses" placeholder="(Default is 10)"/></td>\
</tr><tr>\
    <td><label for="txtVerseSeparators">Verse Separators</label></td>\
    <td><input type="text" id="txtVerseSeparators" name="verseseparators" placeholder="(e.g. 3,6 to put separators after verses 3 and 6)"/></td>\
</tr><tr>\
    <td><label for="txtGenreNumber">Number</label></td>\
    <td><input type="text" id="txtGenreNumber" name="genrenumber" style="width:50px"/>\
    <input type="radio" id="rbGenreNumberLeft" name="genrenumberleftright" value="left" tabindex="-1" checked/><label for="rbGenreNumberLeft">Left</label>\
    <input type="radio" id="rbGenreNumberRight" name="genrenumberleftright" value="right" tabindex="-1"/><label for="rbGenreNumberRight">Right</label></td>\
</tr><tr>\
    <td><label for="txtSpaceBeforeFirstSystem">Space Above First System</label></td>\
    <td><input type="text" id="txtSpaceBeforeFirstSystem" name="spacebeforefirstsystem" placeholder="(Default is -4pt)"/></td>\
</tr><tr>\
    <td><label for="txtSpaceBetweenSystems">Space Between Systems</label></td>\
    <td><input type="text" id="txtSpaceBetweenSystems" name="spacebetweensystems" placeholder="(Default: 12pt plus 1fil minus 8pt)"/></td>\
</tr><tr>\
    <td><label for="txtLyricPadding">Lyric Padding</label></td>\
    <td><input type="text" id="txtLyricPadding" name="lyricPadding" placeholder="(Default is 1)"/></td>\
</tr><tr>\
    <td><label for="txtSpaceAfterLastSystem">Space Above Text-Only Verses</label></td>\
    <td><input type="text" id="txtSpaceAfterLastSystem" name="spaceafterlastsystem" placeholder="(Default is 2pt)"/></td>\
</tr><tr>\
    <td><label for="txtSpaceBeforeMetadata">Space Above Metadata</label></td>\
    <td><input type="text" id="txtSpaceBeforeMetadata" name="spacebeforemetadata" placeholder="(Default is 0pt)"/></td>\
</tr><tr>\
    <td><label for="txtExtraVersesColumnLengths">Extra Verses Column Lengths</label></td>\
    <td><input type="text" id="txtExtraVersesColumnLengths" name="extraVersesColumnLengths" placeholder="(e.g., 1,5 to put a pair of 1-verse columns followed by a pair of 5-verse)"/></td>\
</tr><tr>\
    <td><label for="cbOneColumnExtraVerses">One Column Extra Verses</label></td>\
    <td><input type="checkbox" id="cbOneColumnExtraVerses" name="oneColumnExtraVerses"/></td>\
</tr><tr>\
    <td><label for="cbHideMetadata">Hide Metadata</label></td>\
    <td><input type="checkbox" id="cbHideMetadata" name="hideMetadata"/></td>\
</tr><tr>\
    <td><label for="cbHideTitle">Hide Title</label></td>\
    <td><input type="checkbox" id="cbHideTitle" name="hideTitle"/></td>\
</tr>'/*<tr>\
    <td><label for="cbRaggedLast">Ragged Last Line</label></td>\
    <td><input type="checkbox" tabindex="-1" id="cbRaggedLast" name="raggedlast" value="t"/></td>\
</tr>'*/,
    text: '<tr>\
    <td></td>\
    <td><button id="createSection" type="button" disabled>New version for this text</button><a tabindex="-1" class="remove-button del-section" href="#"></a></td>\
</tr><tr class="sectionRow">\
    <td><label for="sectionID">Load section</label></td>\
    <td><input type="text" id="sectionID" name="sectionID"/></td>\
</tr><tr class="title">\
    <td><label for="txtGenre"><a tabindex="-1" target="_blank" href="../texts.php#autocompletes/title.txt">Title</a></label></td>\
    <td><input type="text" id="txtGenre" autocomplete="title" name="title"/></td>\
</tr><tr>\
    <td><label for="txtGenreNumber">Marginal Number</label></td>\
    <td><input type="text" id="txtGenreNumber" name="genrenumber"/></td>\
</tr><tr>\
    <td><label for="txtGenreQualifier"><a tabindex="-1" target="_blank" href="../texts.php#autocompletes/genreQualifiers.txt">Title Qualifier</a></label></td>\
    <td><input type="text" id="txtGenreQualifier" name="genrequalifier"/></td>\
</tr><tr>\
    <td><label for="txtEngraving"><a tabindex="-1" target="_blank">Reference</a></label></td>\
    <td><input type="text" id="txtEngraving" name="reference"/></td>\
</tr>',
    rubric: '<tr class="title">\
    <td><label for="txtGenre"><a tabindex="-1" target="_blank" href="../texts.php#autocompletes/title.txt">Title</a></label></td>\
    <td><a tabindex="-1" class="remove-button del-section" href="#"></a><div style="margin-right:24px"><input type="text" id="txtGenre" autocomplete="title" name="title"/></div></td>\
</tr><tr>\
    <td>Title Font Size</td>\
    <td><div id="radioRubricTitleSize"><input type="radio" id="radioRubricTitleSize15" checked value="15" class="donotclear" name="rubrictitlesize"/><label for="radioRubricTitleSize15">15pt</label>\
        <input type="radio" id="radioRubricTitleSize12" value="12" class="donotclear" name="rubrictitlesize"/><label for="radioRubricTitleSize12">12pt</label></div></td>\
</tr><tr>\
    <td>Title Alignment</td>\
    <td><div id="radioRubricTitleAlignment"><input type="radio" id="radioRubricTitleAlignmentLeft" value="left" class="donotclear" name="rubrictitlealignment"/><label for="radioRubricTitleAlignmentLeft">Left</label>\
        <input type="radio" id="radioRubricTitleAlignmentCenter" value="center" checked class="donotclear" name="rubrictitlealignment"/><label for="radioRubricTitleAlignmentCenter">Center</label></div></td>\
</tr><tr>\
    <td><label for="txtEngraving"><a tabindex="-1" target="_blank">Rubric</a></label></td>\
    <td><textarea class="engraving" id="txtEngraving" name="rubric"></textarea></td>\
</tr><tr>\
    <td>Text Font Size</td>\
    <td><div id="radioRubricSize"><input type="radio" id="radioRubricSize10" checked value="10" class="donotclear" name="rubricsize"/><label for="radioRubricSize15">10pt</label>\
        <input type="radio" id="radioRubricSize12" value="12" class="donotclear" name="rubricsize"/><label for="radioRubricSize12">12pt</label></div></td>\
</tr><tr>\
    <td>Text Alignment</td>\
    <td><div id="radioRubricTextAlignment"><input type="radio" id="radioRubricTextAlignmentLeft" value="left" checked class="donotclear" name="rubrictextalignment"/><label for="radioRubricTextAlignmentLeft">Left</label>\
        <input type="radio" id="radioRubricTextAlignmentCenter" value="center" class="donotclear" name="rubrictextalignment"/><label for="radioRubricTextAlignmentCenter">Center</label></div></td>\
</tr>',
    'antiphon-tone': '<tr class="genre">\
    <td><label for="txtGenre"><a tabindex="-1" target="_blank" href="../texts.php#autocompletes/genre.txt">Genre</a></label></td>\
    <td><a tabindex="-1" class="remove-button del-section" href="#"></a><div style="margin-right:24px"><input type="text" id="txtGenre" name="genre" autocomplete="genre"/></div></td>\
</tr><tr>\
    <td><label for="txtGenreQualifier"><a tabindex="-1" target="_blank" href="../texts.php#autocompletes/genreQualifiers.txt">Genre Qualifier</a></label></td>\
    <td><input type="text" id="txtGenreQualifier" name="genrequalifier"/></td>\
</tr><tr>\
    <td>Siglia Left</td>\
    <td><input type="checkbox" tabindex="-1" id="cbSigliaLeftRM" value="RM" name="sigliaLeft"/><label for="cbSigliaLeftRM">RM</label>\
        <input type="checkbox" tabindex="-1" id="cbSigliaLeftGR" value="GR" name="sigliaLeft"/><label for="cbSigliaLeftGR">GR</label>\
        <input type="checkbox" tabindex="-1" id="cbSigliaLeftGS" value="GS" name="sigliaLeft"/><label for="cbSigliaLeftGS">GS</label>\
        <input type="checkbox" tabindex="-1" id="cbSigliaLeftL" value="L" name="sigliaLeft"/><label for="cbSigliaLeftL">L</label>\
        <input type="checkbox" tabindex="-1" id="cbSigliaLeftIcon-white" value="Icon-white" name="sigliaLeft"/><label for="cbSigliaLeftIcon-white"><img class="siglia-icon" src="../library/~icons/white.png"/></label>\
        <input type="checkbox" tabindex="-1" id="cbSigliaLeftIcon-half" value="Icon-half" name="sigliaLeft"/><label for="cbSigliaLeftIcon-half"><img class="siglia-icon" src="../library/~icons/half.png"/></label>\
        <input type="checkbox" tabindex="-1" id="cbSigliaLeftIcon-black" value="Icon-black" name="sigliaLeft"/><label for="cbSigliaLeftIcon-black"><img class="siglia-icon" src="../library/~icons/black.png"/></label>\
        <input type="checkbox" tabindex="-1" id="cbSigliaLeftIcon-asterisk" value="Icon-asterisk" name="sigliaLeft"/><label for="cbSigliaLeftIcon-asterisk"><img class="siglia-icon" src="../library/~icons/asterisk.png"/></label>\
    </td>\
</tr><tr>\
    <td>Siglia Right</td>\
    <td><input type="checkbox" tabindex="-1" id="cbSigliaRightRM" value="RM" name="sigliaRight"/><label for="cbSigliaRightRM">RM</label>\
        <input type="checkbox" tabindex="-1" id="cbSigliaRightGR" value="GR" name="sigliaRight"/><label for="cbSigliaRightGR">GR</label>\
        <input type="checkbox" tabindex="-1" id="cbSigliaRightGS" value="GS" name="sigliaRight"/><label for="cbSigliaRightGS">GS</label>\
        <input type="checkbox" tabindex="-1" id="cbSigliaRightL" value="L" name="sigliaRight"/><label for="cbSigliaRightL">L</label>\
        <input type="checkbox" tabindex="-1" id="cbSigliaRightIcon-white" value="Icon-white" name="sigliaRight"/><label for="cbSigliaRightIcon-white"><img class="siglia-icon" src="../library/~icons/white.png"/></label>\
        <input type="checkbox" tabindex="-1" id="cbSigliaRightIcon-half" value="Icon-half" name="sigliaRight"/><label for="cbSigliaRightIcon-half"><img class="siglia-icon" src="../library/~icons/half.png"/></label>\
        <input type="checkbox" tabindex="-1" id="cbSigliaRightIcon-black" value="Icon-black" name="sigliaRight"/><label for="cbSigliaRightIcon-black"><img class="siglia-icon" src="../library/~icons/black.png"/></label>\
        <input type="checkbox" tabindex="-1" id="cbSigliaRightIcon-asterisk" value="Icon-asterisk" name="sigliaRight"/><label for="cbSigliaRightIcon-asterisk"><img class="siglia-icon" src="../library/~icons/asterisk.png"/></label>\
    </td>\
</tr><tr>\
    <td><label for="txtMode">Mode</label></td>\
    <td><input type="text" id="txtMode" name="mode"/></td>\
</tr><tr>\
    <td><label for="selMediant">Mediant</label></td>\
    <td><select id="selMediant" name="mediant">\
      <option>0</option><option>1</option><option selected>2</option>\
    </select></td>\
</tr><tr>\
    <td><label for="selTermination">Termination</label></td>\
    <td><select id="selTermination" name="termination">\
      <option>0</option><option>1</option><option selected>2</option>\
    </select></td>\
</tr><tr>\
    <td><label for="txtEngraving"><a tabindex="-1" target="_blank">Text</a></label></td>\
    <td><input type="text" id="txtEngraving" name="reference"/></td>\
</tr><tr>\
    <td><a tabindex="-1" target="_blank" href="../texts.php#autocompletes/overridetextleft.txt">Override Text-Left</a></td>\
    <td><input type="text" id="txtOverrideTextLeft" name="overridetextleft"/></td>\
</tr><tr>\
    <td><a tabindex="-1" target="_blank" href="../texts.php#autocompletes/overridetextright.txt">Override Text-Right</a></td>\
    <td><input type="text" id="txtOverrideTextRight" name="overridetextright"/></td>\
</tr><tr>\
    <td><label for="selPsalmTone"><a tabindex="-1" target="_blank">Psalm Tone</a></label></td>\
    <td><input type="text" id="selPsalmTone" name="psalmtone"/></td>\
</tr><tr>\
    <td><label for="txtPsalmToneWidth">Psalm Tone Width</label></td>\
    <td><input type="text" id="txtPsalmToneWidth" name="psalmToneWidth" placeholder="(in inches, Default is 1.7)"/></td>\
</tr>', //ENGRAVING SQUARE!
    'engraving-Square': '<tr>\
    <td></td>\
    <td><button id="createSection" type="button" disabled>New version for this engraving</button><a tabindex="-1" class="remove-button del-section" href="#"></a></td>\
</tr><tr class="sectionRow">\
    <td><label for="sectionID">Load section</label></td>\
    <td><input type="text" id="sectionID" name="sectionID"/></td>\
</tr><tr>\
    <td><label for="txtEngravingHeader">Header</label></td>\
    <td><input type="text" id="txtEngravingHeader" name="engravingHeader"/></td>\
</tr><tr class="genre">\
    <td><label for="txtGenre"><a tabindex="-1" target="_blank" href="../texts.php#autocompletes/genre.txt">Genre</a></label></td>\
    <td><input type="text" id="txtGenre" name="genre" autocomplete="genre"/></td>\
</tr><tr>\
    <td><label for="txtGenreQualifier"><a tabindex="-1" target="_blank" href="../texts.php#autocompletes/genreQualifiers.txt">Genre Qualifier</a></label></td>\
    <td><input type="text" id="txtGenreQualifier" name="genrequalifier"/></td>\
</tr><tr class="overrideFilename hidden" style="display:none">\
    <td><label for="txtOverrideFilename">Override Filename</label></td>\
    <td><input type="text" id="txtOverrideFilename" name="overrideFilename"/></td>\
</tr><tr><td colspan="2" class="engravings"><hr class="engraving">\
      <a href="#" class="add-engraving above">Add Engraving</a></td></tr><tr>\
    <td colspan="2"><hr class="engraving"></td>\
</tr><tr>\
    <td><label for="selPsalmTone"><a tabindex="-1" target="_blank">Psalm Tone</a></label></td>\
    <td><input type="text" id="selPsalmTone" name="psalmtone"/></td>\
</tr><tr>\
    <td colspan="2"><label for="cbHarmonizedPsalmTone">Harmonized Psalm Tone</label>\
    <input type="checkbox" tabindex="-1" id="cbHarmonizedPsalmTone" name="harmonizedpsalmtone"/></td>\
</tr><tr>\
    <td><label for="cbTwoColumnVerses">2 Column Verses</label></td>\
    <td><input type="checkbox" tabindex="-1" id="cbTwoColumnVerses" name="twocolumnverses"/></td>\
</tr>' + addVerseButton, // ENGRAVING MODERN! ENGRAVING MODERN!
    'engraving-Modern': '<tr>\
    <td></td>\
    <td><button id="createSection" type="button" disabled>New version for this engraving</button><a tabindex="-1" class="remove-button del-section" href="#"></a></td>\
</tr><tr class="sectionRow">\
    <td><label for="sectionID">Load section</label></td>\
    <td><input type="text" id="sectionID" name="sectionID"/></td>\
</tr><tr>\
    <td><label for="txtEngravingHeader">Header</label></td>\
    <td><input type="text" id="txtEngravingHeader" name="engravingHeader"/></td>\
</tr><tr class="genre">\
    <td><label for="txtGenre"><a tabindex="-1" target="_blank" href="../texts.php#autocompletes/genre.txt">Genre</a></label></td>\
    <td><input type="text" id="txtGenre" name="genre" autocomplete="genre"/></td>\
</tr><tr>\
    <td><label for="txtGenreQualifier"><a tabindex="-1" target="_blank" href="../texts.php#autocompletes/genreQualifiers.txt">Genre Qualifier</a></label></td>\
    <td><input type="text" id="txtGenreQualifier" name="genrequalifier"/></td>\
</tr><tr><td colspan="2" class="engravings"><hr class="engraving">\
      <a href="#" class="add-engraving above">Add Engraving</a></td></tr><tr>\
    <td colspan="2"><hr class="engraving"></td>\
</tr><tr>\
    <td><label for="selPsalmTone"><a tabindex="-1" target="_blank">Psalm Tone</a></label></td>\
    <td><input type="text" id="selPsalmTone" name="psalmtone"/></td>\
</tr><tr>\
    <td colspan="2"><label for="cbHarmonizedPsalmTone">Tone Below</label>\
    <input type="checkbox" tabindex="-1" id="cbHarmonizedPsalmTone" checked name="harmonizedpsalmtone"/></td>\
</tr><tr>\
    <td><label for="cbTwoColumnVerses">2 Column Verses</label></td>\
    <td><input type="checkbox" tabindex="-1" id="cbTwoColumnVerses" name="twocolumnverses"/></td>\
</tr>' + addVerseButton
  };
  var rubricAmongVersesHtml = verseGroupBeginningHtml + sectionHtml.rubric + verseGroupEndingHtml;
  var spaceAmongVersesHtml = verseGroupBeginningHtml + sectionHtml.space + verseGroupEndingHtml;
  var hiddenHtml = '<input type="hidden" id="sectionNum" name="sectionnum[]" class="donotclear"/>\
<input type="hidden" id="sectionJson" name="sectionJson[]"/>\
<input type="hidden" id="cbRaggedLast" name="raggedlast[]"/>\
<input type="hidden" id="sectionID" name="sectionID[]"/>\
<input type="hidden" id="sectionType" name="sectiontype[]"/>\
<input type="hidden" id="mainEngraving" name="mainEngraving[]" value="0"/>\
<input type="hidden" id="txtGenre" name="genre[]"/>\
<input type="hidden" id="txtGenreNumber" name="genrenumber[]"/>\
<input type="hidden" id="txtGenreQualifier" name="genrequalifier[]"/>\
<input type="hidden" id="txtSpaceBeforeFirstSystem" name="spacebeforefirstsystem[]"/>\
<input type="hidden" id="txtSpaceBetweenSystems" name="spacebetweensystems[]"/>\
<input type="hidden" id="txtLyricPadding" name="lyricPadding[]"/>\
<input type="hidden" id="txtSpaceAfterLastSystem" name="spaceafterlastsystem[]"/>\
<input type="hidden" id="txtSpaceBeforeMetadata" name="spacebeforemetadata[]"/>\
<input type="hidden" id="txtEngraving" name="engraving[]"/>\
<input type="hidden" id="cbRemoveTranslation" name="removetranslation[]"/>\
<input type="hidden" id="siglia" name="siglia[]"/>\
<input type="hidden" id="selSpacing" value="" name="spacing[]"/>\
<input type="hidden" id="selAddToEngraving" name="addtoengraving[]"/>\
<input type="hidden" id="selPsalmTone" name="psalmtone[]"/>\
<input type="hidden" id="cbHarmonizedPsalmTone" value="1" name="harmonizedpsalmtone[]"/>\
<input type="hidden" id="selSpaceBelowChant" value="0" name="spacebelowchant[]"/>\
<input type="hidden" id="selSpaceAboveChant" value="0" name="spaceabovechant[]"/>\
<input type="hidden" id="radioRubricTitleSize" value="15" name="rubrictitlesize[]"/>\
<input type="hidden" id="radioRubricTitleAlignment" value="center" name="rubrictitlealignment[]"/>\
<input type="hidden" id="radioRubricSize" value="10" name="rubricsize[]"/>\
<input type="hidden" id="radioRubricTextAlignment" value="left" name="rubrictextalignment[]"/>\
<input type="hidden" id="txtHymnHeader" value="" name="hymnHeader[]"/>\
<input type="hidden" id="txtHymnSupertitle" value="" name="hymnsupertitle[]"/>\
<input type="hidden" id="txtHymnSubtitle" value="" name="hymnsubtitle[]"/>\
<input type="hidden" id="txtNumVerses" value="0" name="numverses[]"/>';
  var clickedDelVerse = function(e) {
    e.preventDefault();
    var $tbl = $(this).parents('table').first(),
        s = $tbl.attr('section'),
        vNum = $tbl.attr('verse');

    $tbl.remove();
    $('input[type=hidden][id$=_'+s+'_'+vNum+']').remove();
  };
  var clickedAddVerseRubric = function(e) {
    var s = $(this).parents('tr').last().attr('section');
    var vNum = numVerses[s]++;
    var sectionVerse = s + '_' + vNum;
    var $rubricHtml = $(rubricAmongVersesHtml);
    $rubricHtml.attr('type','rubric');

    var $newElems = $rubricHtml.filter('table');
    $newElems.addClass('section'+s).attr('section',s);
    $newElems.addClass('verse'+vNum).attr('verse',vNum);
    $('.del-section',$newElems).removeClass('del-section').addClass('del-verse');
    $('tr.title',$newElems).addClass('verselabel');
    $('[id]',$newElems).attr('id',function(i,val) {
      return val + '_' + sectionVerse;
    });
    $('[for]',$newElems).attr('for',function(i,val) {
      return val + '_' + sectionVerse;
    });
    $('input[type=radio]',$newElems).attr('name',function(i,val) {
      return val + '_' + sectionVerse;
    });
    
    var goesBeforeVerse = $(this).parents('table').first().attr('verse');
    if(goesBeforeVerse) {
      $(this).parents('table[verse]').first().before($rubricHtml);
    } else { // Goes after last section
      $(this).parents('ul.menu').first().siblings().last().before($rubricHtml);
    }
    $('a[href=#]:not(ul.menu a):not(label a)',$rubricHtml).button();
    $("ul.menu",$rubricHtml).menu({select: function(e,ui){e.preventDefault();}}).width(26).find('span.ui-icon').remove();
    $('ul.menu ul',$rubricHtml).mouseleave(function(){hideMenu($(this).parents('ul.menu').last());});
    $('.add-verse',$rubricHtml).click(clickedAddVerse);
    $('.del-verse',$rubricHtml).click(clickedDelVerse);
    $("textarea",$rubricHtml).autosize();
    $('tr.verselabel',$rubricHtml).css('cursor','move').draggable({axis:'y',cursor:'move',revert:'invalid',scope:'verse-section'+s});
    $rubricHtml.droppable({scope:'verse-section'+s,tolerance:'touch',over:droppedVerse});
    
    if(e.originalEvent) $('input[name=verselabel]',$rubricHtml).focus();
  }
  var clickedAddVerseSpace = function(e) {
    var s = $(this).parents('tr').last().attr('section');
    var vNum = numVerses[s]++;
    var sectionVerse = s + '_' + vNum;
    var $spaceHtml = $(spaceAmongVersesHtml);
    $spaceHtml.attr('type','space');

    var $newElems = $spaceHtml.filter('table');
    $newElems.addClass('section'+s).attr('section',s);
    $newElems.addClass('verse'+vNum).attr('verse',vNum);
    $('.del-section',$newElems).removeClass('del-section').addClass('del-verse');
    $('tr.title',$newElems).addClass('verselabel');
    $('[name=sectionID]',$newElems).attr('name','space');
    $('[id]',$newElems).attr('id',function(i,val) {
      return val + '_' + sectionVerse;
    });
    $('[for]',$newElems).attr('for',function(i,val) {
      return val + '_' + sectionVerse;
    });
    $('input[type=radio]',$newElems).attr('name',function(i,val) {
      return val + '_' + sectionVerse;
    });
    
    var goesBeforeVerse = $(this).parents('table').first().attr('verse');
    if(goesBeforeVerse) {
      $(this).parents('table[verse]').first().before($spaceHtml);
    } else { // Goes after last section
      $(this).parents('ul.menu').first().siblings().last().before($spaceHtml);
    }
    $('a[href=#]:not(ul.menu a):not(label a)',$spaceHtml).button();
    $("ul.menu",$spaceHtml).menu({select: function(e,ui){e.preventDefault();}}).width(26).find('span.ui-icon').remove();
    $('ul.menu ul',$spaceHtml).mouseleave(function(){hideMenu($(this).parents('ul.menu').last());});
    $('.add-verse',$spaceHtml).click(clickedAddVerse);
    $('.del-verse',$spaceHtml).click(clickedDelVerse);
    $("textarea",$spaceHtml).autosize();
    $('tr.verselabel',$spaceHtml).css('cursor','move').draggable({axis:'y',cursor:'move',revert:'invalid',scope:'verse-section'+s});
    $spaceHtml.droppable({scope:'verse-section'+s,tolerance:'touch',over:droppedVerse});
    
    if(e.originalEvent) $('input[name=verselabel]',$spaceHtml).focus();
  }
  var clickedAddVerse = function(e) {
    e.preventDefault();
    switch($(this).attr('type')) {
      case 'rubric':
        clickedAddVerseRubric.apply(this,[e]);
        return;
      case 'space':
        clickedAddVerseSpace.apply(this,[e]);
        return;
    }
    var s = $(this).parents('tr').last().attr('section');
    var vNum = numVerses[s]++;
    var sectionVerse = s + '_' + vNum;
    var $verseHtml = $(singleVerseHtml);
    $("#rbMarkVersesNumbers,#rbMarkVersesReferenceNumbers,#rbMarkVersesVersicle,#rbMarkVersesNothing,#cbNotateVerses,#cbMarkPenultimateAccent,#cbAllowPageBreaksMidVerse,#txtPsalmTitle,#txtVerseLabel,#cbPageBreakBeforeVerse",$verseHtml).change(txtChanged);
    $("#cbPsalmIntact",$verseHtml).change(psalmIntactChanged);
    $("#cbGloryBe",$verseHtml).change(gloryBeChanged);
    $("#txtPsalmTitle",$verseHtml).keyup(keyUpPsalmTitle).keydown(keyDownUpdatePsalmText).focusin(focusInPsalmTitle).blur(focusOutPsalmTitle)
      .autocomplete({
        source: '../ac_verse.php',
        minLength: 0
      });
    $("#txtPsalmVerse",$verseHtml).keyup(psalmVerseKeyUp).change(psalmVerseKeyUp);
    lstVerseSource[sectionVerse] = '';
    setVerseEditions($("#selVerseSource",$verseHtml),'',sectionVerse);
    $("#selVerseSource",$verseHtml).change(verseEditionChanged);
    $("#txtVerseLabel",$verseHtml).autocomplete({
      source: "../ac.php?root=verselabel",
      minLength: 0,
      delay: 0,
      select: triggerChangeFromAutocomplete
    }).keydown(autocompleteKeyDown);
    $("#txtVerseFile",$verseHtml).change(txtVerseFileChanged).keyup(txtVerseFileChanged).keydown(keyDownUpdatePsalmText).blur(updatePsalmText).autocomplete({
      source: "../ac.php?root=verses/~/&extension=json",
      minLength: 0,
      delay: 0,
      select: triggerChangeFromAutocomplete
    }).keydown(autocompleteKeyDown);
    
    var $newElems = $verseHtml.filter('table');
    $newElems.addClass('section'+s).attr('section',s);
    $newElems.addClass('verse'+vNum).attr('verse',vNum);
    $('[id]',$newElems).attr('id',function(i,val) {
      return val + '_' + sectionVerse;
    });
    $('[for]',$newElems).attr('for',function(i,val) {
      return val + '_' + sectionVerse;
    });
    $('input[type=radio]',$newElems).attr('name',function(i,val) {
      return val + '_' + sectionVerse;
    });
    
    var goesBeforeVerse = $(this).parents('table').first().attr('verse');
    if(goesBeforeVerse) {
      $(this).parents('table[verse]').first().before($verseHtml);
    } else { // Goes after last section
      $(this).parents('ul.menu').first().siblings().last().before($verseHtml);
    }
    $('a[href=#]:not(ul.menu a):not(label a)',$verseHtml).button();
    $("ul.menu",$verseHtml).menu({select: function(e,ui){e.preventDefault();}}).width(26).find('span.ui-icon').remove();
    $('ul.menu ul',$verseHtml).mouseleave(function(){hideMenu($(this).parents('ul.menu').last());});
    $('.add-verse',$verseHtml).click(clickedAddVerse);
    $('.del-verse',$verseHtml).click(clickedDelVerse);
    $("textarea",$verseHtml).autosize();
    $('tr.verselabel',$verseHtml).css('cursor','move').draggable({axis:'y',cursor:'move',revert:'invalid',scope:'verse-section'+s});
    $verseHtml.droppable({scope:'verse-section'+s,tolerance:'touch',over:droppedVerse});
    
    if(e.originalEvent) $('input[name=verselabel]',$verseHtml).focus();
  };
  var clickedDelEngraving = function(e) {
    e.preventDefault();
    $(this).parents('table[section][engraving]').first().remove();
  };
  var setupSiglia = function($html) {
    $('input[type=checkbox][value=Icon-white],input[type=checkbox][value=Icon-half]',$html).change(function(){
      if(this.checked) {
        $that = $('input[name="'+this.name+'"][type=checkbox][value=Icon-white],input[name="'+this.name+'"][type=checkbox][value=Icon-half]',$html).not(this);
        $that.prop('checked',false);
      }
    });
  }
  var clickedAddEngraving = function(e) {
    e.preventDefault();
    var s = $(this).parents('tr').last().attr('section');
    var eNum = numEngravings[s]++;
    var sectionEngraving = s + '_' + eNum;
    if(eNum>0 && !$('#sectionID_'+s).val().match(/^~?(hybrid|gospel-verses)\//)) {
      $('#sectionID_'+s).val('').keyup();
    }
    var engravingType = sectionType[s].match(/(Square|Modern)$/) || [0,'Square'];
    engravingType = engravingType[1];
    
    var $engravingHtml = $(singleEngravingHtml[engravingType]);
    $engravingHtml.find('#txtEngraving,#selSpacing,#txtSpaceBetweenSystems,#cbRaggedLast').change(txtChanged);
    if(eNum == 0) {
      $engravingHtml.addClass('main');
    }
    $("#selSpacing",$engravingHtml).keyup(txtChanged);
    $("#selAddToEngraving",$engravingHtml).change(addToEngravingChanged).keyup(addToEngravingChanged);
    setupSiglia($engravingHtml);
    $("input[name=engraving]",$engravingHtml).keyup(txtEngravingKeyUp).autocomplete({
      source: "../ac_engraving.php?type="+engravingType.toLowerCase(),
      select: updateScore,
      minLength: 0
    });
    $("#txtEngravingLabel",$engravingHtml).autocomplete({
      source: "../ac.php?root=engravinglabel",
      minLength: 0,
      delay: 0,
      select: triggerChangeFromAutocomplete
    }).keydown(autocompleteKeyDown);
    $("#txtOverrideTextLeft",$engravingHtml).autocomplete({
      source: "../ac.php?root=overridetextleft",
      minLength: 0,
      delay: 0
    }).keydown(autocompleteKeyDown);
    $("#txtOverrideTextRight",$engravingHtml).autocomplete({
      source: "../ac.php?root=overridetextright",
      minLength: 0,
      delay: 0
    }).keydown(autocompleteKeyDown);
    
    $engravingHtml.addClass('section'+s).attr('section',s);
    $engravingHtml.addClass('engraving'+eNum).attr('engraving',eNum);
    $('[id]',$engravingHtml).attr('id',function(i,val) {
      return val + '_' + sectionEngraving;
    });
    $('[for]',$engravingHtml).attr('for',function(i,val) {
      return val + '_' + sectionEngraving;
    });
    $('input[type=radio]',$engravingHtml).attr('name',function(i,val) {
      return val + '_' + sectionEngraving;
    });
    
    var goesBeforeEngraving = $(this).parents('table[engraving]').attr('engraving');
    if(goesBeforeEngraving) {
      $(this).parents('table[engraving]').first().before($engravingHtml);
    } else { // Goes after last section
      $(this).siblings().last().before($engravingHtml);
    }
    $('a[href=#]:not(label a)',$engravingHtml).button();
    $('.add-engraving',$engravingHtml).click(clickedAddEngraving);
    $('.del-engraving',$engravingHtml).click(clickedDelEngraving);
    $('tr.engravinglabel',$engravingHtml).css('cursor','move').draggable({axis:'y',cursor:'move',revert:'invalid',scope:'engraving-section'+s});
    $engravingHtml.droppable({scope:'engraving-section'+s,tolerance:'touch',over:droppedEngraving});
    
    if(e.originalEvent) $('input[name=engravinglabel]',$engravingHtml).focus();
  };
  var clickedAddSection = function(e) {
    var focusOnSection = !e.isTrigger;
    e.preventDefault();
    hideAllSections();
    var $this = $(this);
    var type = $this.attr("type");
    if(type=='engraving')type += '-' + _types[selType];
    var engravingType = type.match(/(Square|Modern)$/);
    if(engravingType) {
      engravingType = engravingType[1];
    } else {
      engravingType = '';
    }
    sectionType[numSections] = type;
    numVerses[numSections] = 0;
    numEngravings[numSections] = 0;
    var $sectionHtml = $(sectionSeparatorHtml + sectionHtml[type]);
    setupSiglia($sectionHtml);
    $("#txtGenre,#txtGenreQualifier,#cbRaggedLast,#txtGenreNumber,#txtSpaceBetweenSystems,#txtLyricPadding,#txtSpaceAfterLastSystem,#txtSpaceBeforeFirstSystem,#txtSpaceBeforeMetadata,#txtHymnSupertitle,#txtHymnHeader,#txtHymnSubtitle,#cbRemoveTranslation,#cbOverrideTextLeft,#txtOverrideTextLeft,#cbOverrideTextRight,#txtOverrideTextRight,#selPsalmTone,#cbHarmonizedPsalmTone,#selSpaceBelowChant,#selSpaceAboveChant,#radioRubricTitleSize12,#radioRubricTitleSize15,#radioRubricSize12,#radioRubricSize10,#radioRubricTitleAlignmentLeft,#radioRubricTitleAlignmentCenter,#radioRubricTextAlignmentLeft,#radioRubricTextAlignmentCenter,#txtNumVerses",$sectionHtml).change(txtChanged);
    $("#selPsalmTone",$sectionHtml).keyup(txtChanged).keyup(updateScore).change(updateScore).on('keyup change',function(){
      var thisType = type.match(/-(\S+)$/)[1].toLowerCase();
      $this.parents('tr').first().find('a').attr('href',this.value?'../engraver#'+thisType+'/'+this.value:null);
    });
    $("#sectionID",$sectionHtml).keyup(selectSectionID).change(selectSectionID);
    $("button",$sectionHtml).button().click(createNewSection);
    //$("div[id^=radioRubricTitleSize]",$sectionHtml).buttonset();
    $("[id^=cbSiglia]",$sectionHtml).change(sigliaChanged);
    
    var $pdffHtml = $(hiddenHtml);
    var $imgfHtml = $(hiddenHtml);
    var $newElems = $sectionHtml.filter('tr').add($pdffHtml).add($imgfHtml);
    $newElems.filter("[id=sectionType]").val(type);
    $newElems.filter("[name='sectionnum[]']").val(numSections);
    $newElems.addClass('section'+numSections).attr('section',numSections);
    $('[id]',$newElems).attr('id',function(i,val) {
      return val + '_' + numSections;
    });
    $('[for]',$newElems).attr('for',function(i,val) {
      return val + '_' + numSections;
    });
    $('input[type=radio]',$newElems).attr('name',function(i,val) {
      return val + '_' + numSections;
    });
    $pdffHtml.attr('id',function(i,val) {
      return 'pdff_' + val + '_' + numSections;
    });
    $imgfHtml.attr('id',function(i,val) {
      return 'imgf_' + val + '_' + numSections;
    });
    $this.parents('tr').first().before($sectionHtml);

    var goesBeforeSection = $this.parents('tr').first().attr('section');
    if(!goesBeforeSection) { // Goes after last section
      $('#pdff_txtFooter').before($pdffHtml);
      $('#imgf_txtFooter').before($imgfHtml);
    } else {
      $('#pdff_sectionNum_' + goesBeforeSection).before($pdffHtml);
      $('#imgf_sectionNum_' + goesBeforeSection).before($imgfHtml);
    }
    $("ul.menu",$sectionHtml).menu({select: function(e,ui){e.preventDefault();}}).width(26).find('span.ui-icon').remove();
    $('ul.menu ul',$sectionHtml).mouseleave(function(){hideMenu($(this).parents('ul.menu').last());});
    $('a[href=#]:not(ul.menu a):not(label a)',$sectionHtml).button();
    $('.add-verse',$sectionHtml).click(clickedAddVerse);
    $("#selPsalmTone_" + numSections).attr('engravingType',engravingType.toLowerCase());
    var pTones = engravingType=='Modern'? psalmTonesModern : psalmTones;
    if(pTones.length) {
      $("#selPsalmTone_" + numSections).autocomplete({
        source: pTones,
        select: updateScore,
        minLength: 0,
        delay: 0
      });
    }
    $("#txtGenreQualifier_" + numSections).autocomplete({
      source: "../ac.php?root=genreQualifiers",
      select: selectGenreQualifier,
      minLength: 0,
      delay: 0
    }).keydown(autocompleteKeyDown);

    $("#txtHairlineText_" + numSections).autocomplete({
      source: "../ac.php?root=hairlineTexts",
      minLength: 0,
      delay: 0
    });
    
    //$("#selPsalmTone_" + numSections).keyup(txtChanged).keyup(updateScore).change(updateScore);
    if(type=='rubric') {
      $("#txtEngraving_" + numSections).change(txtChanged);
    } else {
      $("#txtEngraving_" + numSections).keyup(txtEngravingKeyUp).autocomplete({
        source: type=='text'?"../ac.php?root=texts/" : type=='antiphon-tone'? "../ac.php?root=texts/antiphons/&extension=json" : type=='hymn'?'../ac_engraving.php?type=modern' : "../ac_engraving.php?type="+engravingType.toLowerCase(),
        select: type=='text'?updateReference : updateScore,
        minLength: 0
      });
    }
    $("#sectionID_" + numSections).autocomplete({
      source: "../ac_sectionID.php?type="+type,
      select: selectSectionID,
      minLength: 0
    });
    /*$("#txtSpaceBelowChant_" + numSections).autocomplete({
      source: ['0in','0.2441in'],
      minLength: 0,
      delay: 0,
      select: updateSpaceBelowChant
    });*/
    $("#txtGenre_" + numSections + "[autocomplete=genre]").autocomplete({
      source: "../ac.php?root=genre",
      minLength: 0,
      delay: 0,
      select: updateGenre
    }).keydown(autocompleteKeyDown);
    $("#txtGenre_" + numSections +"[autocomplete=title]").autocomplete({
      source: "../ac.php?root=title",
      minLength: 0,
      delay: 0,
      select: updateGenre
    }).keydown(autocompleteKeyDown);
    $('tr.title.section'+ numSections +',tr.genre.section' + numSections).css('cursor','move').draggable({axis:'y',cursor:'move',revert:'invalid',scope:'section'});
    $('tr.separator.section' + numSections).droppable({scope:'section',tolerance:'touch',over:droppedSection});
    $('hr.verse',$sectionHtml).droppable({scope:'verse-section'+numSections,tolerance:'touch',over:droppedVerse});
    $('td.engravings hr.engraving',$sectionHtml).droppable({scope:'engraving-section'+numSections,tolerance:'touch',over:droppedEngraving});
    $(".add-engraving",$sectionHtml).click(clickedAddEngraving).click();
    $('#selSpace_'+numSections,$sectionHtml).keyup(updateSelSpace).change(updateSelSpace).change();
    
    ++numSections;
    if(focusOnSection) {
      hideAllSections(numSections - 1);
      $sectionHtml.find('input[tabindex!=-1],select,textarea').first().focus();
    }
    //for some reason calling .menu('collapseAll',0,true); didn't work, so let's do things by hand...
    $menu = $this.parents('ul.menu').last();
    hideMenu($menu);
  };
  var hideMenu = function($menu){
    $menu.find('ul').hide().attr('aria-expanded','false');
    $menu.find('a').removeClass('ui-state-focus ui-state-active');
  }
  var droppedSection = function(e,ui) {
    var target = this;
    var $dropped = ui.draggable;
    var s = $dropped.attr('section');
    var moveBefore = $(target).attr('section');
    var $sectionRows = $('tr[section='+s+']');

    if($sectionRows.index(target)>=0) return;
    var $pdfSectionRows = $('#pdfForm input[section='+s+']');
    var $imgSectionRows = $('#imageForm input[section='+s+']');
    if(moveBefore) {
      $('tr[section='+moveBefore+']').first().before($sectionRows);
      $('#pdfForm input[type=hidden][section='+moveBefore+']').first().before($pdfSectionRows);
      $('#imageForm input[type=hidden][section='+moveBefore+']').first().before($imgSectionRows);
    } else {
      var $insertAfter = $('tr[section]').last();
      if($sectionRows.index($insertAfter)>=0) return;
      $('tr[section]').last().after($sectionRows);
      $('#pdfForm input[type=hidden][section]').last().after($pdfSectionRows);
      $('#imageForm input[type=hidden][section]').last().after($imgSectionRows);
    }
  };
  var droppedVerse = function(e,ui) {
    var target = this;
    var $dropped = ui.draggable.parents('table').first();
    var s = $dropped.attr('section');
    var v = $dropped.attr('verse');
    var moveBefore = $(target).attr('verse');
    if(moveBefore == v) return;
    var $pdfVerseRows = $('#pdfForm input[section='+s+'][verse='+v+']');
    var $imgVerseRows = $('#imageForm input[section='+s+'][verse='+v+']');
    $(target).before($dropped);
    if(moveBefore) {
      $('#pdfForm input[type=hidden][section='+s+'][verse='+moveBefore+']').first().before($pdfVerseRows);
      $('#imageForm input[type=hidden][section='+s+'][verse='+moveBefore+']').first().before($imgVerseRows);
    } else {
      $('#pdfForm input[type=hidden][section='+s+'][verse]').last().after($pdfVerseRows);
      $('#imageForm input[type=hidden][section'+s+'][verse]').last().after($imgVerseRows);
    }
  };
  var droppedEngraving = function(e,ui) {
    var target = this;
    var $dropped = ui.draggable.parents('table').first();
    var s = $dropped.attr('section');
    var eNum = $dropped.attr('engraving');
    var moveBefore = $(target).attr('engraving');
    if(moveBefore == eNum) return;
    $(target).before($dropped);
  };
  $('tr.finalSeparator').droppable({scope:'section',tolerance:'touch',over:droppedSection});
  var clickedDelSection = function(e) {
    e.preventDefault();
    var section = $(this).parents('tr').attr('section');
    $('[section='+section+']').remove();
  };
  var clickedOverrideTextLeft = function(e){
    if(e.ctrlKey || e.shiftKey || e.altKey) return;
    e.preventDefault();
    var $label = $(this).parents('label').first();
    var $cb = $label.siblings('input[type=checkbox]');
    var cb = $cb.get(0);
    cb.checked = !cb.checked;
    $cb.change();
  };
  var cbOverrideTextLeftChanged = function(e){
    var id = 'txt' + this.id.slice(2);
    var $elem = $('#imgf_' + id + ',#pdff_' + id);
    if(this.checked) {
      $('#' + id).removeAttr('disabled').focus();
      $elem.val($('#' + id).val())
    } else {
      $('#' + id).val('').change().attr('disabled', 'disabled');
      $elem.val('null');
    }
  }
  $(document.body)
    .on("click","a.add-section",clickedAddSection)
    .on("click","a.del-section",clickedDelSection)
    .on('blur','[id^=txtPsalmTitle]',updatePsalmText)
    .on('focusin','input,textarea,select',onFocus)
    .on('click','tr[section]:not(.separator):not(.buttonrow) td',onFocus)
    .on('click','a.override-text-left,a.override-text-right',clickedOverrideTextLeft)
    .on('change','[id^=cbOverrideTextLeft],[id^=cbOverrideTextRight],#cbOverrideHeader',cbOverrideTextLeftChanged);
  $("ul.menu").menu({select: function(e,ui){e.preventDefault();}}).width(26).find('span.ui-icon').remove();
  $('ul.menu ul').mouseleave(function(){hideMenu($(this).parents('ul.menu').last());});
  $("#txtEdition").autocomplete({
    source: "../ac.php?root=scores/&extension=/",
    minLength: 0,
    select: updateEdition,
    delay: 0
  }).keydown(autocompleteKeyDown);
  $("#txtTemplate").keyup(updateTemplateLink).autocomplete({
    source: "../ac.php?root=score-templates/&extension=json",
    minLength: 0,
    select: updateEdition,
    delay: 0
  });
  var psalmTones = [];
  var psalmTonesModern = [];
  var liturgy = {
    table: [],
    titles: [],
    dates: [],
    secondaryTitles: [],
    mapTitlessShortname: {},
    mapTitleSuperSubShortname: {},
    mapTitleSupertitle: {},
    mapTitleSubtitle: {},
    mapTitleSuperSub: {},
    mapTitleSubSuper: {},
    mapSuperTitle: {},
    getArray: function(key) {
      var result = [];
      for(var i in this.table) {
        var title = this.table[i][key];
        if(!title) continue;
        if(result.indexOf(title) < 0) result.push(title);
      }
      return result.sort();
    },
    map: function(key,val){
      keys = [].slice.apply(arguments,[0,-1]);
      key = keys.join('|');
      val = [].slice.apply(arguments,[-1])[0];
      var result = {};
      for(var i in this.table) {
        var row = this.table[i];
        var curKey = [];
        for(var j in keys) {
          curKey.push(row[keys[j]])
        }
        if(curKey.join('').length==0) continue;
        var type = typeof(result[curKey]);
        switch(type) {
          case 'string':
            if(result[curKey] == row[val]) break; // Don't add a duplicate.
            result[curKey] = [result[curKey]];
            // I want execution to fall through:
          case 'object':
            result[curKey].push(row[val]);
            break;
          default:
            result[curKey] = row[val];
            break;
        }
        
      }
      return result;
    }
  };
  window.liturgy = liturgy;
  $.getJSON("../ac_psalmTone.php?type=square",function(data){
    psalmTones = data;
    $("input[name=psalmTone][engravingType=square]").autocomplete({
      source: psalmTones,
      select: updateScore,
      minLength: 0,
      delay: 0
    });
  });
  $.getJSON("../ac_psalmTone.php?type=modern",function(data){
    psalmTonesModern = data;
    $("input[name=psalmTone][engravingType=modern]").autocomplete({
      source: psalmTonesModern,
      select: updateScore,
      minLength: 0,
      delay: 0
    });
  });
  $.getJSON('../verse_editions.php',function(data){
    verseEditions = data;
  });
  $.get('../library/liturgy.txt',function(data){
    var rows = data.split('\n');
    var result = [];
    var label = rows[0].split('|');
    var numPipes = label.length - 1;
    for(var i = 1; i < rows.length;) {
      var rowText = rows[i];
      while(++i < rows.length && (rowText.match(/\|/g)||[]).length < numPipes) {
        rowText += '\n' + rows[i];
      }
      var myRow = rowText.split('|');
      if(myRow.length < numPipes) break;
      var myObject = {};
      for(var j in myRow) {
        myObject[label[j]] = myRow[j];
      }
      result.push(myObject);
    }
    liturgy.table = result;
    liturgy.titles = liturgy.getArray('Title');
    liturgy.dates = liturgy.getArray('Date');
    liturgy.secondaryTitles = liturgy.getArray('secondaryTitle');
    liturgy.mapTitlessShortname = liturgy.map('Title','Date','Secondary Title','Shortname');
    liturgy.mapTitleSuperSubShortname = liturgy.map('Title','Date','Secondary Title','Shortname');
    liturgy.mapTitleSupertitle = liturgy.map('Title','Date');
    liturgy.mapTitleSubtitle = liturgy.map('Title','Secondary Title');
    liturgy.mapSuperTitle = liturgy.map('Date','Title');
    liturgy.mapTitleSuperSub = liturgy.map('Title','Date','Secondary Title');
    liturgy.mapTitleSubSuper = liturgy.map('Title','Secondary Title','Date');
    $("#txtTitle").autocomplete({
      source: liturgy.titles,
      select: titleChanged,
      minLength: 0,
      delay: 0
    });
    $("#txtSupertitle").autocomplete({
      source: liturgy.dates,
      select: supertitleChanged,
      minLength: 0,
      delay: 0
    });
    $("#txtSubtitle").autocomplete({
      source: liturgy.secondaryTitles,
      select: subtitleChanged,
      minLength: 0,
      delay: 0
    });
  });

  $("#lnkGregorio").click(callGregorioImage);
  $("#lnkGregorioPDF,#lnkSmallPDF").click(callGregorioPdf);
  $("#lnkSectionPDF").click(callSectionPdf);
  $("#lnkPublish,#lnkSaveGregorio").click(callGregorio);
  $("#lnkClear").click(clearFields);
  $("#txtEdition,#txtTemplate,#txtSupertitle,#txtTitle,#txtSubtitle,#txtFooter,#txtFilename,#txtOverrideTextLeft,#txtOverrideTextRight,#txtOverrideHeader,#rbMarginalNumbers12pt,#rbMarginalNumbers8pt,#rbMarginalNumbersAlignTextAboveStaff,#rbMarginalNumbersAlignGenre,#cbSwapMarginalNumbers,#cbBoldMarginalNumbers").change(txtChanged);
  $("#txtFooter").keyup(txtFooterKeyUp).autocomplete({
    source: "../ac.php?root=footers/&extension=txt&hideExtension=1",
    select: updateFooterText,
    minLength: 0
  })
  $('#txtTitle').keyup(titleChanged).change(titleChanged);
  $('#txtSupertitle').keyup(supertitleChanged).change(supertitleChanged);
  $('#txtSubtitle').keyup(subtitleChanged).change(subtitleChanged);
  $('#cbOverrideSigliaIcon-white,#cbOverrideSigliaIcon-half').change(function(){
    if(this.checked) {
      $that = $('[id^=cbOverrideSigliaIcon-white],[id^=cbOverrideSigliaIcon-half]').not(this);
      $that.prop('checked',false);
    }
  });
  $("[id^=cbOverrideSiglia]").change(sigliaOverrideChanged);

  
  if(location.protocol.slice(0,4) != "http" ||
     !location.hostname.match(/(?:www\.)?(?:illuminarepublications|sacredmusicproject)\.com/i)
    ) {
    processUrl = "http://www.illuminarepublications.com/dev/processPsalm.php";
    dirUrl = "http://www.illuminarepublications.com/dev/dir.php";
    $("#imageForm,#pdfForm").attr("action",processUrl);
  }
  $(document).keydown(docKeyDown);
  $("svg").detach();
  $("#chant-image").hide().click(hideImage);
  $("#overlay").click(hideImage);
  $('#cbOverrideFilename').change(function(e){
    var $txtFilename = $('#txtFilename');
    if(this.checked) {
      $txtFilename.removeAttr('disabled');
    } else {
      $txtFilename.attr('disabled','disabled');
      $('[id$=txtFilename]').val('');
      updateFilename();
    }
    $txtFilename.change().focus();
  });
  $('#btnAntiphonOnly').button().click(function(e){
    $('input[type=hidden][name=includeverses]').val('');
    $('input[name=filename]').val($('#txtFilename').val() + '_no-verses');
    $('input[type=checkbox][class=whitespace]').prop('checked',false).change();
    $(this).prop('disabled',true).button('refresh');
  });
  $("#txtLoadScore").click(function(){$(this).autocomplete('search');}).autocomplete({
    source: "../ac.php?root=scores/&extension=json",
    select: selectLoadScore,
    minLength: 0
  });
  
  $.QueryString = (function (a) {
      if (a == "") return {};
      var b = {};
      for (var i = 0; i < a.length; ++i) {
          var p = a[i].split('=');
          if (p.length != 2) continue;
          b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
      }
      if (b.successMsg) showAlert(false, b.successMsg);
      if (b.failMsg) showAlert(true, b.failMsg);
      return b;
  })(window.location.search.substr(1).split('&'));
  var loadDoc = window['loadDoc'] = function(url) {
    clearFields();
    if(typeof(url)!='string' || url=='') return;
    if(!url.match(/^library\//)) {
      url = '../get.php?file=scores/' + url;
    }
    $.ajax({
      url: url, dataType: 'json', cache: false,
      success: function(data,textStatus,jqXHR){
        if(typeof(data.title) != 'string') return;
        var rubricI = 0;
        $('[id$=txtEdition]').val(data.edition);
        $('[id$=txtSupertitle]').val(data.supertitle);
        $('[id$=txtTitle]').val(data.title);
        $('[id$=txtFooter]').val((data.footer || "").replace(/\r?\n/g,'\n'));
        $('[id$=txtTemplate').val(data.template);
        updateTemplateLink();
        var includeverses = data.includeverses===''?'' : 1;
        $('input[type=hidden][name=includeverses]').val(includeverses);
        $('#btnAntiphonOnly').prop('disabled',!includeverses).button('refresh');
        if(data.marginalnumbersize) {
          $('input[name=marginalnumbersize][value='+data.marginalnumbersize+']').prop('checked',true).change();
        }
        if(data.marginalnumberalignment) {
          $('input[name=marginalnumberalignment][value='+data.marginalnumberalignment+']').prop('checked',true).change();
        }
        $('#cbSwapMarginalNumbers').prop('checked',data.swapmarginalnumbers && parseInt(data.swapmarginalnumbers));
        $('#cbBoldMarginalNumbers').prop('checked',data.boldmarginalnumbers && parseInt(data.boldmarginalnumbers));
        $('[id$=f_cbSwapMarginalNumbers').val(data.swapmarginalnumbers);
        $('[id$=f_cbBoldMarginalNumbers').val(data.boldmarginalnumbers);
        checkFooter();
        $('[id$=txtSubtitle]').val(typeof(data.subtitle)=='string'?data.subtitle : '');
        if(data.filename) {
          $('#txtFilename').removeAttr('disabled');
          $('#cbOverrideFilename').attr('checked',true);
          $('[id$=txtFilename]').val(data.filename);
        } else {
          $('#txtFilename').attr('disabled','disabled');
          $('#cbOverrideFilename').removeAttr('checked');
          $('[id$=txtFilename]').val('');
          updateFilename();
          if(!includeverses) {
            $('[id$=txtFilename]').val($('#txtFilename').val() + '_no-verses');
          }
        }
        if(typeof(data.globalOverrideTextLeft)=='string' && data.globalOverrideTextLeft !== 'null') {
          $('#txtOverrideTextLeft').removeAttr('disabled');
          $('#cbOverrideTextLeft').attr('checked',true);
          $('[id$=txtOverrideTextLeft]').val(data.globalOverrideTextLeft);
        }
        if(typeof(data.globalOverrideTextRight)=='string' && data.globalOverrideTextRight !== 'null') {
          $('#txtOverrideTextRight').removeAttr('disabled');
          $('#cbOverrideTextRight').attr('checked',true);
          $('[id$=txtOverrideTextRight]').val(data.globalOverrideTextRight);
        }
        if(typeof(data.globalOverrideHeader)=='string' && data.globalOverrideHeader !== 'null') {
          $('#txtOverrideHeader').removeAttr('disabled');
          $('#cbOverrideHeader').attr('checked',true);
          $('[id$=txtOverrideHeader]').val(data.globalOverrideHeader);
        }
        if(data.overrideSiglia) {
          $('[id$=overrideSiglia').val(data.overrideSiglia);
          $.each(data.overrideSiglia.split(/,\s*/), function(i,o) {
            $('#cbOverrideSiglia' + o).attr('checked',true);
          });
        }
        var section = data.sectionID || data.engraving;
        var sectionsToLoad=[];
        var numSectionsLoaded=0;
        var numSectionsWithError=0;
        var numSectionsToProcess=section.length;
        var numSectionsProcessed=0;
        var processSection = function() {
          var i = numSectionsProcessed;
          // Add section...
          var type = (data.sectiontype&&data.sectiontype[i]) || 'engraving-Square';
          sectionType[i] = type;
          var subtype = '';
          var maintype= type.match(/^(\w+)(?:-|$)/)[1];
          if(type.match(/^engraving/)){
            subtype = (type.slice(10) || _types[0]);
            type = maintype + '-' + subtype;
          }
          var dir=(type=='text')?'text-sections/':'engraving-sections/'+subtype.toLowerCase()+'/';
          selType = _types.indexOf(subtype);
          if(selType < 0) selType = 0;
          setTypeLabel();
          $('a.add-section[type='+type+']').last().click();
          $('[id$=txtGenreQualifier_' + i + ']').val((data.genrequalifier&&data.genrequalifier[i])||'');
          if(type.match(/^rubric/)) {
            var rubric = data.rubrics[rubricI++];
            loadSection(rubric,i,type,false);
            processNextSection();
            return;
          }
          var sectionData = {
            sectiontype: type,
            sectionJson: data.sectionJson && data.sectionJson[i] && (typeof(data.sectionJson[i])=='string'? JSON.parse(data.sectionJson[i]) : data.sectionJson[i]),
            sectionID: data.sectionID && data.sectionID[i],
            genre: data.genre && data.genre[i],
            genrenumber: data.genrenumber && data.genrenumber[i],
            genrenumberleftright: data.genrenumberleftright && data.genrenumberleftright[i],
            siglia: data.siglia && data.siglia[i],
            engravinglabel: data.engravinglabel && data.engravinglabel[i],
            spaceabovechant: data.spaceabovechant && data.spaceabovechant[i],
            spacebelowchant: data.spacebelowchant && data.spacebelowchant[i],
            hidetextleft: data.hidetextleft && data.hidetextleft[i],
            overridetextleft: (data.overridetextleft && data.overridetextleft[i]),
            overridetextright: (data.overridetextright && data.overridetextright[i]) ,
            genrequalifier: data.genrequalifier && data.genrequalifier[i],
            engraving: data.engraving && data.engraving[i],
            addtoengraving: typeof(data.addtoengraving)=='string'? data.addtoengraving : (data.addtoengraving && data.addtoengraving[i]),
            psalmtone: data.psalmtone && data.psalmtone[i],
            raggedlast: data.raggedlast && data.raggedlast[i],
            //psalmtitle: data.psalmtitle && data.psalmtitle[i],
            psalmverse: typeof(data.psalmverse)=='string'? data.psalmverse : (data.psalmverse && data.psalmverse[i]),
            glorybe: data.glorybe && data.glorybe[i],
            spacing: (data.spacing && $.type(data.spacing)=='array' && data.spacing[i]) || '',
            spacebeforefirstsystem: (data.spacebeforefirstsystem && data.spacebeforefirstsystem[i]) || '',
            spacebetweensystems: (data.spacebetweensystems && data.spacebetweensystems[i]) || '',
            lyricPadding: (data.lyricPadding && data.lyricPadding[i]) || '',
            spaceafterlastsystem: (data.spaceafterlastsystem && data.spaceafterlastsystem[i]) || '',
            spacebeforemetadata: (data.spacebeforemetadata && data.spacebeforemetadata[i]) || '',
            numverses: (data.numverses && data.numverses[i]) || '',
            hymnHeader: (data.hymnHeader && data.hymnHeader[i]) || '',
            hymnsupertitle: (data.hymnsupertitle && data.hymnsupertitle[i]) || '',
            hymnsubtitle: (data.hymnsubtitle && data.hymnsubtitle[i]) || '',
            pagebreakbeforeverse: (data.pagebreakbeforeverse && data.pagebreakbeforeverse[i]) || ''
          };
          //When elements from verse sections are saved to the score file, they are not put into the normalized order, but depend on the sectionnum array.
          if(data.sectionnum) {
            var newI = parseInt(data.sectionnum[i]);
            if(newI >= 0 && newI != i) {
              for (var j = verseVars.length - 1; j >= 0; j--) {
                var key = verseVars[j];
                if(key in sectionData && $.isArray(sectionData[key])) {
                  sectionData[key] = (data[key] && data[key][newI]) || sectionData[key];
                }
              }
            }
          }
          
          var loadSectionFromCurrentData = function(){
            loadSection(sectionData,i,type,false);
          };
          if(data.sectionID && data.sectionID[i] && data.sectiontype[i]!='space') {
            sectionsToLoad.push({
              url:'../get.php?file=' + dir + data.sectionID[i] + '.json',
              i: i,
              type: type,
              sectionData: sectionData,
              loadSectionFromCurrentData: loadSectionFromCurrentData
            });
          } else {
            loadSectionFromCurrentData();
          }
          processNextSection();
        };
        var updateProgressBarWithNumLoaded = function() {
          if(numSectionsLoaded >= sectionsToLoad.length) {
            // we're done loading!
            $(".loading").hide();
            $("#progressBar").progressbar({value: 0});
          } else {
            $("#progressBar").progressbar({value: numSectionsLoaded});
          }
        }
        var loadNextSection = function(i){
          if(i < sectionsToLoad.length) {
            var my = sectionsToLoad[i];
            $.ajax({
              url: my.url,
              dataType: 'json',
              cache: false,
              success: function(data,status,jqXHR){
                setTimeout(function(data){
                  if($.isArray(data.engraving)) {
                    delete data['spacebelowchant'];
                    delete data['spaceabovechant'];
                  }
                  $.extend(my.sectionData,data);
                  loadSection(my.sectionData,my.i,my.type,false);
                  numSectionsLoaded++;
                  console.info('Loaded ' + numSectionsLoaded + ' of ' + sectionsToLoad.length + ' sections');
                  updateProgressBarWithNumLoaded();
                }, 0, data);
              },
              error: function(jqXHR,status,error){
                setTimeout(function(error){
                  console.info('Error on section ' + my.url);
                  console.error(error);
                  numSectionsLoaded++;
                  numSectionsWithError++;
                  if(jqXHR.status == 404) {
                    loadSection(my.sectionData,my.i,my.type,false);
                  }
                }, 0, error);
              }
            });
            loadNextSection(i+1);
          }
        };
        var processNextSection = function(){
          if(++numSectionsProcessed < numSectionsToProcess) {
            setTimeout(processSection,0,i);
            $("#progressBar").progressbar({value: numSectionsProcessed});
          } else {
            $('#progressText').text('Loading... (Phase 2/2)');
            $("#progressBar").progressbar({value: 0, max: sectionsToLoad.length});
            updateProgressBarWithNumLoaded();
            loadNextSection(0);
          }
          console.info('Processed ' + numSectionsProcessed + ' of ' + numSectionsToProcess + ' sections');
        };
        $("#progressBar").progressbar({value: 0, max: numSectionsToProcess});
        $('#progressText').text('Loading... (Phase 1/2)');
        setTimeout(processSection,0,0);
        $(".loading").show();
        hideAllSections();
      }
    });
  }
  var loadSectionVerseRubric = function(data,sv){
    $('[id$=txtGenre_' + sv + ']').val(data.title||'');
    $('[id$=radioRubricTitleSize'+data.rubrictitlesize+'_' + sv + ']').attr('checked',true).trigger('change');
    var alignment = data.rubrictitlealignment[0].toUpperCase() + data.rubrictitlealignment.slice(1);
    $('[id$=radioRubricTitleAlignment'+alignment+'_' + sv + ']').attr('checked',true).trigger('change');
    $('[id$=txtEngraving_' + sv + ']').val(data.rubric||'');
    $('[id$=radioRubricSize'+data.rubricsize+'_' + sv + ']').attr('checked',true).trigger('change');
    alignment = data.rubrictextalignment[0].toUpperCase() + data.rubrictextalignment.slice(1);
    $('[id$=radioRubricAlignment'+alignment+'_' + sv + ']').attr('checked',true).trigger('change');
  };
  var loadSectionVerseSpace = function(data,sv){
    $('[id$=selSpace_' + sv + ']').val(data.space||'');
  };
  var loadSectionVerse = function(data,sv){
    data.glorybe = data.glorybe&&(data.glorybe===true)||parseInt(data.glorybe);
    $('[id$=txtVerseFile_' + sv + ']').val(data.versefile||'');
    $('[id$=txtVerseLabel_' + sv + ']').val(data.verselabel||'');
    $('[id$=txtPsalmTitle_' + sv + ']').val(data.psalmtitle||'');
    if(data.psalmverse && !data.glorybe) {
      $('[id$=txtPsalmVerse_' + sv + ']').val(data.psalmverse).trigger('autosize.resize').trigger('change');
    }
    $('[id$=cbGloryBe_' + sv + ']').attr('checked',(data.glorybe)?true:false).trigger('change');
    if(data.numberverses) {
      var nv = parseInt(data.numberverses);
      $('[id$=rbMarkVerses'+(nv?'Numbers':'Versicle')+'_' + sv + ']').attr('checked',true).trigger('change');
    } else if(data.markverses) {
      var mv = data.markverses[0].toUpperCase() + data.markverses.slice(1);
      $('[id$=rbMarkVerses'+mv+'_' + sv + ']').attr('checked',true).trigger('change');
    }
    $('[id$=cbPageBreakBeforeVerse_' + sv + ']').prop('checked',data.pagebreakbeforeverse&&(data.pagebreakbeforeverse===true)||parseInt(data.pagebreakbeforeverse)?true:false).trigger('change');
    $('[id$=cbNotateVerses_' + sv + ']').attr('checked',(data.notateverses&&(data.notateverses===true)||parseInt(data.notateverses))?true:false).trigger('change');
    $('[id$=cbMarkPenultimateAccent_' + sv + ']').attr('checked',(data.markpenultimateaccent&&(data.markpenultimateaccent===true)||parseInt(data.markpenultimateaccent))?true:false).trigger('change');
    $('[id$=cbAllowPageBreaksMidVerse_' + sv + ']').attr('checked',(data.allowpagebreaksmidverse&&(data.allowpagebreaksmidverse===true)||parseInt(data.allowpagebreaksmidverse))?true:false).trigger('change');
    keyUpPsalmTitle.apply($('[id$=txtPsalmTitle_' + sv + ']')[0],[undefined,true]);
  };
  var loadSectionEngraving = function(data,s,e,engravingType){
    var $table = $('table.section'+s+'.engraving'+e);
    switch(data.spacing) {
      case 'vichi': 
      case 'smith':
        break;
      default:
        data.spacing = '';
        break;
    }
    for(key in data) {
      if(key=='siglia' && data[key]) {
        var val = data[key];
        if(typeof(val)=='string') val = val.split(/\s*,\s*/);
        $.each(val,function(){
          $('[name=siglia][value='+this+']',$table).attr('checked',true);
        });
      } else {
        $input = $('[name='+key+'],[name='+key+'_'+s+'_'+e+']',$table);
        switch($input.prop('type')) {
          case 'checkbox':
            $input.attr('checked', (data[key] && data[key]!='0' && data[key]!='')?true:false);
            break;
          case 'radio':
            {
              var dataKey = data[key];
              if($.isArray(dataKey)) {
                dataKey = dataKey[0];
              }
              $input.filter('[value='+dataKey+']').attr('checked',true);
            }
            break;
          default:
            var id = $input.attr('id');
            var cb = id && $('#cb' + id.match(/[A-Z].*$/)[0]).get(0);
            if(cb) {
              cb.checked = (typeof(data[key]) == 'string');
              $(cb).change();
              if(!cb.checked) data[key]='';
            }
            $input.val(data[key]);
        }
      }
    }
    $table.toggleClass('main',data.main?true:false);
    if($.isArray(data.engraving)) data.engraving = data.engraving[0];
    $('input[name=engraving]',$table).val(data.engraving).parents('tr').first().find('a').attr('href','../engraver#'+engravingType+'/' + data.engraving);
    $('[id$=selSpaceBelowChant_' + s + '_' + e + ']').val((data.spacebelowchant == '0.2441')? '15.6' : (data.spacebelowchant || '7.8')).trigger('change');
    $('[id$=selSpaceAboveChant_' + s + '_' + e + ']').val((data.spaceabovechant == '0.2441')? '15.6' : (data.spaceabovechant || '0')).trigger('change');
    if(data.main && data.engraving) {
      lstEngravingName[s] = data.engraving;
      $.ajax({
        url:'../get.php?file=engravings/'+engravingType+'/' + lstEngravingName[s],
        cache: false,
        success: function(data) {
          if(typeof(data)=='object'){
            //MODERN engraving
            lstEngraving[s] = data
          } else {
            data = data.replace(/\s+$/,'');
            var header = getHeader(data);
            
            delete header.cValues.spacing;
            delete header.cValues.width;
            delete header.cValues.height;
            lstEngraving[s] = header + data.slice(header.original.length);
          }
        }
      });
    }
  }
  var verseVars = ['verselabel','pagebreakbeforeverse','versesource','versefile','psalmtitle','markverses','notateverses','markpenultimateaccent','allowpagebreaksmidverse','glorybe','psalmverse'];
  var loadSection = window['loadSection'] = function(data,s,type,clearFields){
    $('table.section' + s + ' a.del-verse').click();
    numVerses[s] = 0;
    numEngravings[s] = 0;
    if(clearFields) {
      $('[id$=_'+s+'].section'+s).not('[type=checkbox]').not('[type=radio]').not('.donotclear').not('table[engraving] *').not('table[verse] *').val('');
      $('[id$=_'+s+'][type=checkbox]').not('table[engraving] *').not('table[verse] *').attr('checked',false);
    }
    if(data.sectionID) {
      $('[id$=sectionID_' + s + ']').val(data.sectionID);
      lstSectionID[s] = data.sectionID;
    }
    $('[id$=txtGenre_' + s + ']').val(data.genre||'');
    $('[id$=txtGenreNumber_'+s+']').val(data.genrenumber||'');
    $('[id$=txtGenreQualifier_'+s+']').val(data.genrequalifier||'');
    if(data.raggedlast == 0) data.raggedlast = '';
    $('[id$=cbRaggedLast_'+s+']').attr('checked', data.raggedlast?true:false).trigger('change');
    var engravingType = 'square';
    $('[id$=sectionType_'+s+']').val(type||data.sectiontype||data.sectionType);
    switch(type||data.sectiontype||data.sectionType){
      case 'hairline':
        $('#txtHairlineText_'+s).val(data.sectionJson && data.sectionJson.text || '');
        $('#txtHairlineMargin_'+s).val(data.sectionJson && data.sectionJson.margin || '');
        break;
      case 'pagebreak':
        break;
      case 'space':
        if(data.sectionID) {
          $('[id$=sectionID_'+s+'],[id$=selSpace_'+s+']').val(data.sectionID);
        }
        break;
      case 'text':
        if(data.engraving) {
          var text = lstEngravingName[s] = data.engraving;
          $('[id$=txtEngraving_' + s + ']').val(text);
          $($("#txtEngraving_" + s).prop('labels')).find('a').attr('href', '../texts.php#texts/' + text + '.txt');
        } else {
          $($("#txtEngraving_" + s).prop('labels')).find('a').attr('href', null);
        }
        break;
      case 'antiphon-tone':
        if(data.sectionJson) {
          var psalmTone = data.psalmtone||'';
          $('[id$=selPsalmTone_' + s + ']').val(psalmTone).parents('tr').first().find('a').attr('href',psalmTone?'../engraver#square/'+psalmTone:null);
          var text = data.sectionJson.text;
          $('[id$=txtEngraving_' + s + ']').val(text);
          $($("#txtEngraving_" + s).prop('labels')).find('a').attr('href', '../texts.php#texts/antiphons/' + text);
          $('[id$=txtOverrideTextLeft_' + s + ']').val(data.sectionJson.overrideTextLeft);
          $('[id$=txtOverrideTextRight_' + s + ']').val(data.sectionJson.overrideTextRight);
          $('[id$=selMediant_' + s + ']').val(data.sectionJson.mediant);
          $('[id$=txtPsalmToneWidth_' + s + ']').val(data.sectionJson.psalmToneWidth);
          $('[id$=selTermination_' + s + ']').val(data.sectionJson.termination);
          if(data.sectionJson.sigliaLeft) {
            var val = data.sectionJson.sigliaLeft.split(/\s*,\s*/);
            $.each(val,function(){
              $('[section='+s+'] [name=sigliaLeft][value='+this+']').attr('checked',true);
            });
          }
          if(data.sectionJson.sigliaRight) {
            val = data.sectionJson.sigliaRight.split(/\s*,\s*/);
            $.each(val,function(){
              $('[section='+s+'] [name=sigliaRight][value='+this+']').attr('checked',true);
            });
          }
        } else {
          $($("#txtEngraving_" + s).prop('labels')).find('a').attr('href', null);
        }
        break;
      case 'rubric':
        $('[id$=txtGenre_' + s + ']').val(data.title||'');
        $('[id$=txtEngraving_' + s + ']').val(data.rubric||'');
        data.titlesize = data.titlesize||15;
        $('input[id$=radioRubricTitleSize_' + s + ']').val(data.titlesize);
        $('#radioRubricTitleSize' + data.titlesize + '_' + s).prop('checked',true);
        data.size = data.size||10;
        $('input[id$=radioRubricSize_' + s + ']').val(data.size);
        $('#radioRubricSize' + data.size + '_' + s).prop('checked',true);
        data.titlealignment = data.titlealignment||'center';
        $('input[id$=radioRubricTitleAlignment_' + s + ']').val(data.titlealignment);
        $('[id^=radioRubricTitleAlignment][value=' + data.titlealignment + '][id$=_' + s + ']').prop('checked',true);
        data.textalignment = data.textalignment||'left';
        $('input[id$=radioRubricTextAlignment_' + s + ']').val(data.textalignment);
        $('[id^=radioRubricTextAlignment][value=' + data.textalignment + '][id$=_' + s + ']').prop('checked',true);
        break;
      case 'hymn':
        var engraving = data.engraving||'';
        var spacebeforefirstsystem = data.spacebeforefirstsystem||'';
        var spacebetweensystems = data.spacebetweensystems||'';
        var lyricPadding = data.lyricPadding||'';
        var spaceafterlastsystem = data.spaceafterlastsystem||'';
        var spacebeforemetadata = data.spacebeforemetadata||'';
        var numverses = parseInt(data.numverses)||'';
        var header = data.hymnHeader||'';
        var supertitle = data.hymnsupertitle||'';
        var subtitle = data.hymnsubtitle||'';
        var genrenumberleftright = data.sectionJson && data.sectionJson['genrenumberleftright'];
        var verseseparators = data.sectionJson && data.sectionJson['verseseparators'];
        var extraVersesColumnLengths = data.sectionJson && data.sectionJson['extraVersesColumnLengths'];
        var oneColumnExtraVerses = data.sectionJson && data.sectionJson['oneColumnExtraVerses'];
        var hideMetadata = data.sectionJson && data.sectionJson['hideMetadata'];
        var hideTitle = data.sectionJson && data.sectionJson['hideTitle'];
        if(verseseparators) verseseparators = JSON.stringify(verseseparators).slice(1,-1);
        $('[id$=txtEngraving_' + s + ']').val(engraving).parents('tr').first().find('a').attr('href','../engraver#modern/' + engraving);
        $('[id$=txtSpaceBeforeFirstSystem_' + s + ']').val(spacebeforefirstsystem);
        $('[id$=txtSpaceBetweenSystems_' + s + ']').val(spacebetweensystems);
        $('[id$=txtLyricPadding_' + s + ']').val(lyricPadding);
        $('[id$=txtSpaceAfterLastSystem_' + s + ']').val(spaceafterlastsystem);
        $('[id$=txtSpaceBeforeMetadata_' + s + ']').val(spacebeforemetadata);
        $('[id$=txtNumVerses_' + s + ']').val(numverses);
        $('[id$=txtHymnHeader_' + s + ']').val(header);
        $('[id$=txtHymnSupertitle_' + s + ']').val(supertitle);
        $('[id$=txtHymnSubtitle_' + s + ']').val(subtitle);
        $('[id$=_'+s+'][name^=genrenumberleftright][value='+genrenumberleftright+']').attr('checked',true);
        $('[id$=txtVerseSeparators_'+s+']').val(verseseparators);
        $('[id$=txtExtraVersesColumnLengths_'+s+']').val(extraVersesColumnLengths);
        $('[id$=cbOneColumnExtraVerses_'+s+']').prop('checked',oneColumnExtraVerses);
        $('[id$=cbHideMetadata_'+s+']').prop('checked',hideMetadata);
        $('[id$=cbHideTitle_'+s+']').prop('checked',hideTitle);
        break;
      case 'engraving-Modern':
        engravingType = 'modern'
        $('[id$=txtSpaceBetweenSystems_' + s + ']').val(data.spacebetweensystems||'');
        //Now fall back into default...
        //NEWSTUFF needed here or perhaps later inline?
      default:
        $('[id$=cbTwoColumnVerses_' + s + ']').prop('checked', data.sectionJson && data.sectionJson.twoColumnVerses);
        $('[id$=txtEngravingHeader_'+ s + ']').val(data.sectionJson && data.sectionJson.engravingHeader);
        if(data.glorybe == 0) data.glorybe = '';
        
        var psalmTone = data.psalmtone||'';
        //This could eventually be removed; it was to account for a name change in the psalm tone files.
        if(psalmTones.indexOf(psalmTone)<0) {
          for(j in psalmTones) {
            var pt = psalmTones[j];
            if(psalmTone.slice(-(pt.length))==pt) {
              psalmTone = pt;
              break;
            }
          }
        }
        
        $engravingTables = $('table[engraving].section' + s);
        $engravingTables.remove();
        var engraving = data.engraving||'';
        if($.isArray(engraving) && typeof(engraving[0])!='string') {
          $.each(data.engraving,function(i){
            $('tr[section='+s+'] .add-engraving.above').click();
            this.genrenumber = (data.genrenumber && data.genrenumber[i]) || this.genrenumber;
            this.engravinglabel = (data.engravinglabel && data.engravinglabel[i]) || this.engravinglabel;
            this.spacebelowchant = (data.spacebelowchant && data.spacebelowchant[i]) || this.spacebelowchant;
            this.spaceabovechant = (data.spaceabovechant && data.spaceabovechant[i]) || this.spaceabovechant;
            this.overridetextleft = ((data.hidetextleft && data.hidetextleft[i]) || this.hidetextleft)? "" :
                                     (data.overridetextleft? data.overridetextleft[i] : this.overridetextleft);
            this.overridetextright = ((data.hidetextright && data.hidetextright[i]) || this.hidetextright)? "" :
                                     (data.overridetextright? data.overridetextright[i] : this.overridetextright);
            this.genrenumberleftright = (data.genrenumberleftright && data.genrenumberleftright[i]) || this.genrenumberleftright;
            this.siglia = (data.siglia && data.siglia[i]) || this.siglia;
            loadSectionEngraving(this,s,i,engravingType);
          });
        } else {
          $('tr[section='+s+'] .add-engraving.above').click();
          data.main = true;
          loadSectionEngraving(data,s,0,engravingType);
        }

        $('[id$=selPsalmTone_' + s + ']').val(psalmTone).parents('tr').first().find('a').attr('href',psalmTone?'../engraver#'+engravingType+'/'+psalmTone:null);
        $('[id$=cbHarmonizedPsalmTone_' + s + ']').attr('checked',!!(data.harmonizedpsalmtone)).trigger('change');
        var nv=0;
        var verseData = [];
        if($.isArray(data.verses)) {
          $.each(data.verses,function(i){
            var curVerseData = this;
            switch(curVerseData.type) {
              case 'rubric':
                $('tr[section='+s+'] ul.above a.add-verse[type=rubric]').last().click();
                loadSectionVerseRubric(curVerseData,s+'_'+nv);
                break;
              case 'space':
                $('tr[section='+s+'] ul.above a.add-verse[type=space]').last().click();
                loadSectionVerseSpace(curVerseData,s+'_'+nv);
                break;
              default:
                $.each(verseVars,function(j,e){
                  curVerseData[e] = (data[e] && data[e][i]) || curVerseData[e];
                });
                $('tr[section='+s+'] ul.above a.add-verse:not([type])').last().click();
                loadSectionVerse(curVerseData,s+'_'+nv);
            }
            verseData.push(curVerseData);
            ++nv;
          });
        } else if($.isArray(data.psalmtitle)) {
          $.each(data.psalmtitle,function(i){
            var curVerseData = {};
            $.each(verseVars,function(j,e){
              curVerseData[e] = data[e] && data[e][i];
            });
            $('tr[section='+s+'] ul.above a.add-verse:not([type])').last().click();
            loadSectionVerse(curVerseData,s+'_'+nv);
            verseData.push(curVerseData);
            ++nv;
          });
        } else {
          verseData=[data];
          nv=1;
          $('tr[section='+s+'] ul.above a.add-verse:not([type])').last().click();
          loadSectionVerse(data,s + '_0');
        }
        numVerses[s] = nv;

        if(psalmTone) {
          if(psalmTone.indexOf('/')<0)psalmTone = 'psalm-tones/' + psalmTone;
          $.get('../get.php?file=engravings/'+engravingType+'/' + psalmTone, function(data) {
            var psalmToneInfo;
            if(engravingType == 'modern') {
              if(data.sop) psalmToneInfo = getPsalmToneInfoLy(data.sop);
            } else {
              data = data.slice(getHeaderLen(data)).replace(/\s+$/,'');
              psalmToneInfo = getPsalmToneInfo(data);
            }
            lstPsalmToneInfo[s] = psalmToneInfo;
            lstPsalmTone[s] = data;
            $.each(verseData,function(i,curVerseData){
              var sectionVerse = s + '_' + i;
              var match = (curVerseData.psalmtitle||'').match(/([\w-]+\.?)\s+(\d+).*/);
              var verseSource = '';
              if(match) verseSource = getVerseSource(match[1]);
              var verseEdition = curVerseData.versesource||'rgp';
              if(verseEdition=='~') {
                verseEdition += '/' + curVerseData.versefile;
              } else if(!match || !verseSource) {
                if(curVerseData.glorybe && curVerseData.psalmverse) {
                  $('#txtPsalmVerse_' + sectionVerse).val(curVerseData.psalmverse + '\n\n' + gloryBe(psalmToneInfo)).trigger('autosize.resize').trigger('change');
                }
                return;
              }
              if(match) $("#txtPsalmTitle_" + sectionVerse).parents('tr').first().find('a').attr('href','../texts.php#verses/' + verseSource + '/' + verseEdition + '/' + match[2] + '.txt');
              var getdata = {
                title: curVerseData.psalmtitle,
                glorybe: (curVerseData.glorybe)||'',
                ms: psalmToneInfo[0] || 0,
                ts: psalmToneInfo[1] || 0,
                source: verseSource,
                edition: verseEdition,
                keepVerseNumbers: 1
              };
              $.get('../psalmref.php', getdata, function(data) {
                if(typeof(data)=='string' && data.length > 0) {
                  data = data.replace(/^\s+|\s+$/g,'').replace(/\r\n/g,'\n');
                  var $psalmVerse = $("#txtPsalmVerse_" + sectionVerse);
                  var trueData = curVerseData.psalmverse;
                  //if the original is the same as what we've got, it is an anomaly.
                  if(trueData && data == trueData) trueData = '';
                  $("#cbPsalmIntact_" + sectionVerse).attr('checked',trueData?false:true);
                  $psalmVerse.attr('title',trueData? data : '');
                  $psalmVerse.val(data).data({original:$psalmVerse.val(),value:trueData});
                  if(trueData) {
                    if(curVerseData.glorybe) {
                      $psalmVerse.val(trueData + '\n\n' + gloryBe(psalmToneInfo)).trigger('autosize.resize').trigger('change');
                    } else {
                      $psalmVerse.val(trueData).trigger('autosize.resize');
                    }
                  }
                  $psalmVerse.trigger('autosize.resize');
                }
              });
            });
          });
        } else { // NO psalmTone
          $.each(verseData,function(i,curVerseData){
            var sectionVerse = s + '_' + i;
            var match = (curVerseData.psalmtitle || '').match(/([\w-]+\.?)\s+(\d+).*/);
            var verseSource = '';
            if(match) verseSource = getVerseSource(match[1]);
            var verseEdition = curVerseData.versesource||'rgp';
            if(verseEdition=='~') {
              verseEdition += '/' + curVerseData.versefile;
            } else if(!match || !verseSource) {
              if(curVerseData.glorybe && curVerseData.psalmverse) {
                $('#txtPsalmVerse_' + sectionVerse).val(curVerseData.psalmverse + '\n\n' + gloryBe(psalmToneInfo)).trigger('autosize.resize').trigger('change');
              }
              return;
            }
            if(match) $("#txtPsalmTitle" + sectionVerse).parents('tr').first().find('a').attr('href','../texts.php#verses/' + verseSource + '/' + verseEdition + '/' + match[2] + '.txt');
            var getdata = {
              title: curVerseData.psalmtitle,
              glorybe: (curVerseData.glorybe)||'',
              ms: 0,
              ts: 0,
              source: verseSource,
              edition: verseEdition,
              keepVerseNumbers: 1
            };
            $.get('../psalmref.php', getdata, function(data) {
              if(typeof(data)=='string' && data.length > 0) {
                data = data.replace(/^\s+|\s+$/g,'').replace(/\r\n/g,'\n');
                var $psalmVerse = $("#txtPsalmVerse_" + sectionVerse);
                var trueData = curVerseData.psalmverse;
                $("#cbPsalmIntact_" + s).attr('checked',trueData?false:true);
                $psalmVerse.attr('title',trueData? data : '');
                $psalmVerse.val(data).data({original:$psalmVerse.val()});
                if(trueData) {
                  if(curVerseData.glorybe) {
                    $psalmVerse.val(trueData + '\n\n' + gloryBe(psalmToneInfo)).trigger('autosize.resize').trigger('change');
                  } else {
                    $psalmVerse.val(trueData).trigger('autosize.resize');
                  }
                }
                $psalmVerse.trigger('autosize.resize');
              }
            });
          });
        }
        break;
    }
  }
  loadDoc($.QueryString.load);
  setTimeout(function(){$("#chant-image-iframe").load(lightboxImage)},1000);
  hideAllSections('title');
});